Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 674
Pratibha Avatar asked Sep 11 '14 12:09

Pratibha


Video Answer


2 Answers

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.

like image 69
Chandermani Avatar answered Oct 05 '22 22:10

Chandermani


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.

like image 22
Johannes Avatar answered Oct 05 '22 23:10

Johannes