[英]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.