简体   繁体   English

AngularJS:无法访问$ scope。$ on中的控制器的范围变量

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

I am trying to access scope variable inside $scope.$on but it returns undefined , but if I use a normal variable it is working fine. 我正在尝试访问$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'
 });
});

Inside your callback for $on , the value of this will be that callback. 里面的回调$on ,值了this将是回调。 And since you haven't defined any property with name a in that call back, it will be undefined . 并且由于您尚未在该回调中定义任何名称为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'
 });
});

you should use $scope.a instead of this.a . 你应该使用$scope.a代替this.a also, b is used wrong as well. 同样, b也被错误地使用。

your code should look like this: 您的代码应如下所示:

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

hope that helps. 希望能有所帮助。

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

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