Search code examples
javascriptangularjscontrollerevent-handlingangularjs-scope

Access to controller scope from $scope.$on in AngularJS


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)?


Solution

  • 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
      })
    }