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: