1

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 ?

lin
  • 17,956
  • 4
  • 59
  • 83
Mouad Ennaciri
  • 1,217
  • 3
  • 15
  • 28

1 Answers1

1

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:

lin
  • 17,956
  • 4
  • 59
  • 83
  • You have an idea why it never goes into the $onDestroy method ? – Mouad Ennaciri Feb 06 '18 at 15:05
  • @MouadEnnaciri Are you using `ui-router`? – lin Feb 06 '18 at 15:30
  • @in Yes, on the other hand enters the method when I change the route – Mouad Ennaciri Feb 06 '18 at 16:31
  • @MouadEnnaciri `$onDestroy` does not work with `ui-router` binded controllers because this event is not delegated by `ui-router`. Please check https://github.com/angular-ui/ui-router/issues/3043 & https://github.com/angular-ui/ui-router/issues/3043 you could create a component instead of a controller to make work or use `$scope.$on('$destroy')`. Glad to help ya – lin Feb 06 '18 at 16:34
  • @MouadEnnaciri any feedback? – lin Feb 07 '18 at 09:12
  • I enter the `$onDestroy` method when I change my route, it's good I think? – Mouad Ennaciri Feb 07 '18 at 11:36