簡體   English   中英

AngularJS:無法訪問$ scope。$ on中的控制器的范圍變量

[英]AngularJS : Not able to access controller's scope variable inside $scope.$on

我正在嘗試訪問$scope.$on作用域變量$scope.$on但它返回undefined ,但是如果我使用普通變量,則可以正常工作。

Example: 

app.controller('myCtrl',function($scope){
 this.a = "hello";
 var b = "hi";
 // some code

 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log(this.a); // prints 'undefined'
  console.log(b);  //prints 'hi'
 });
});

里面的回調$on ,值了this將是回調。 並且由於您尚未在該回調中定義任何名稱為a屬性,因此它將是undefined

app.controller('myCtrl',function($scope){
 this.a = "hello";
 var b = "hi";
 // some code
 var that = this; // <<<<<<<<< 
 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log(that.a); // prints hello
  console.log(b);  //prints 'hi'
 });
});

你應該使用$scope.a代替this.a 同樣, b也被錯誤地使用。

您的代碼應如下所示:

app.controller('myCtrl',function($scope){
 $scope.a = "hello";
 $scope.b = "hi";
 // some code

 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log($scope.a); 
  console.log($scope.b); 
 });
});

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM