2015-09-16 68 views
2

如何在下面的情況下解決變量作用域的問題。Javascript和角度變量作用域問題

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

類似this.someFunctionA()...我想你需要通過調用這個引用你的內部函數。否則,您需要申請,綁定或致電外部。 – Vontei

+0

@Vontei如何申請綁定? –

回答

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

你要麼需要綁定this的功能,或者只是訪問的功能對象屬性是這樣的:

mycont.someFunctionA()