How can i solve the issue of scope of variable in the below case.
Myapp.controller('MyController', ['$scope', function ($scope) { var formvalues = {}; $scope.somebuttonclick = function(){ mycont.somefunctionB(); }; var mycont = { init: function(){ formvalues.init = "some value init"; this.somefunctionA(); }, somefunctionA: function(){ formvalues.a= "some value a"; alert(formvalues.init); //comes undefined when called from mycont.init }, somefuntionB: function(){ formvalues.b = "some valuee b"; alert(formvalues.init); // comes "some value init" when called from buttonclick } }; }]);
Calling through button click, variable are defined correctly but when called from inside of mycont method, it say undefined. How to solve this
你要么需要绑定this
的功能,或者只是访问功能这样的对象属性:
mycont.someFunctionA()
Don't know what exactly you are looking for but check this:
Myapp.controller('MyController', ['$scope','$log', function ($scope, $log) {
var formvalues = {};/*this is empty at first*/
var mycont = {
init: function(){
formvalues.init = "some value init";
},
somefunctionA: function(){
formvalues.a= "some value a";
/*mycont.init();*/ /*you can call it here, if not in somebuttonclick*/
$log.log(formvalues.init);
$log.log(formvalues.a);
},
somefunctionB: function(){
formvalues.b = "some valuee b";
/* mycont.init(); */ /*you can call it here, if not in somebuttonclick*/
$log.log(formvalues.init);
$log.log(formvalues.b);
}
};
$scope.somebuttonclick = function(){
mycont.init();/*you need to first call this function before you can use the value*/
mycont.somefunctionA();
mycont.somefunctionB();
};
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.