Reputation: 3797
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'
});
});
Upvotes: 0
Views: 442
Reputation: 7100
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'
});
});
Upvotes: 2
Reputation: 5461
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.
Upvotes: 1