Search code examples
javascriptangularjsangularjs-scope

AngularJS - $rootScope.$on - Multiple execution


In my $onInit() I pick up the propagation event:

  $onInit() {
    this.$rootScope.$on('CANCELLED', (event) => {
      this.EventService.getEventsCurrentUser('own')
        .then((result) => {
          this.ownEvents = result
        })
      })
  }

How can I stop the propagation at one time ?


Solution

  • You need to "unregister" $rootScope events manually by calling the return function. You can do it with the component lifecycle by using this.$onDestroy. $rootScope events getting binded again and again each time $rootScope.$on() is executed. Thats why your events getting called multiple times.

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope, $rootScope) {
    
      var registerScope = null;
    
      this.$onInit = function () {
        //register rootScope event
        registerScope = $rootScope.$on('CANCELLED', function(event) {
            console.log("fired");
        });
      }
    
      this.$onDestroy = function () {
        //unregister rootScope event by calling the return function
        registerScope();
      }
    });
    

    Please also check this answers which will help you to understand the logic behind $rootScope and $scope events: