簡體   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