0

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

2 Answers 2

2

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'
 });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, a rookie mistake. Thanks.
1

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.

2 Comments

Please update the comment in console.log($scope.a); to show prints hello
I am intentionally using 'this' to use ' controller as' syntax, hence do not want to use $scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.