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 ?

2
  • what you meant by at one time? Commented Feb 6, 2018 at 12:07
  • Don't register the event on the rootscope. Register it on the scope Commented Feb 6, 2018 at 12:11

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

6 Comments

You have an idea why it never goes into the $onDestroy method ?
@MouadEnnaciri Are you using ui-router?
@in Yes, on the other hand enters the method when I change the route
@MouadEnnaciri $onDestroy does not work with ui-router binded controllers because this event is not delegated by ui-router. Please check github.com/angular-ui/ui-router/issues/3043 & 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
@MouadEnnaciri any feedback?
|

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.