繁体   English   中英

Javascript和angular中的变量范围问题

[英]variable scope issue in Javascript and angular

在以下情况下,如何解决变量范围的问题?

 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方法内部调用时,变量未定义。 如何解决这个问题

你要么需要绑定this的功能,或者只是访问功能这样的对象属性:

mycont.someFunctionA()

不知道您到底在寻找什么,但请检查以下内容:

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();
    };
}]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM