如何解决以下情况中变量范围的问题。
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
}
};
}]);

通过按钮单击调用,变量被正确定义但是当从mycont方法内部调用时,它表示未定义。如何解决这个问题
答案 0 :(得分:0)
您需要将this
绑定到函数,或者只是像以下那样访问函数作为对象属性:
mycont.someFunctionA()
答案 1 :(得分:0)
不知道到底在找什么,但请查看:
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();
};
}]);