Angular $rootScope.$broadcast() event caught twice in controller

All we need is an easy explanation of the problem, so here it is.

Broadcating event on button click :-

$scope.onButtonClick = function(){
    $rootScope.$broadcast('onButtonClick');
}

And catching event in another controller :-

$rootScope.$on('onButtonClick',function(event){
  alert("catched");
  console.log(event);
});

But it caught twice even though it fired only once. Why is that?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

As it turned out the multiple controllers were instantiated due to ng-controller declaration in html and also as part of state setup for ui-router.

The solution is to remove one of the declarations.

Method 2

If you broadcast an event on $rootScope, you can catch the event on each controller $scope.
IMO you should not catch the event on the $rootScope.

$scope.$on('onButtonClick',function(event){
  alert("catched");
  console.log(event);
});

I’ve created a plunker showcase, which shows that it works exactly as expected. Plunker

It could be possible that you have multiple instances of the same controller, where you catch the event. Please check this as Chandermani suggested.

Method 3

Angular $rootScope.$broadcast() event caught twice in controller

$scope.$on('saveCancelLeadInfo', function (event, args) {
    if ($scope.$$listenerCount["saveCancelLeadInfo"] > 1) {
        $scope.$$listenerCount["saveCancelLeadInfo"] = 0;
    }
    your code here
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply