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.
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. And since you haven't defined any property with name a
in that call back, it will be 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
. also, b
is used wrong as well.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.