Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm beginner at Angular and I have this simple problem in Angular 1.5. I use rootScope for emit some events and $scope.$on as the event listener in component controller (which provide data for child components). This controller contains some complex object, which must be modified by incoming event data. Controller looks like this (just example):

function ComponentController($scope){

  this.abc = 5;

  $scope.$on('BOOM!', function(events, args){
    console.log(args);
    this.abc = this.abc + args;  // example of modifying some controllers data
  })
}

Problem is clear - I can't modify this.abc. So how can I access to controllers data and modify them within this event listener? When I use $scope.abc instead, it works, but is it necessary (when I use everywhere controllerAs)?

share|improve this question
up vote 0 down vote accepted

It should solve your issue

function ComponentController($scope){
  var vm = this;
  vm.abc = 5;

  $scope.$on('BOOM!', function(events, args){
    console.log(args);
    vm.abc = vm.abc + args;  // example of modifying some controllers data
  })
}
share|improve this answer
1  
Thanks. it works. The problem is just in the scope (event listener has own scope with own this)? I didnt thought that before. – chobotek Dec 30 '16 at 13:40
function ComponentController($scope){
  //Assign this to that, this is in the scope/context of ComponentController.   
  var that = this.
  that.abc = 5;

  $scope.$on('BOOM!', function(events, args){
    //the this used here earlier was in the scope/context of the function to handle this event
    // therefore we use the that variable assigned in the ComponentController.
    console.log(args);
    that.abc = that.abc + args;  // example of modifying some controllers data
  })
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.