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

3

25

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?

Lessen answered 11/9, 2014 at 12:55 Comment(5)
Most probably two instances of the controller are active. One common reason is use of $routeProvider controller and ng-controller on the same view.Kial
so how to resolve it? can you please help me?Lessen
Do you have your controller instantiated in view with ng-controller as Chandermani suggested? If so, remove the ng-controller attribute. Instantiating the controller with ng-controller, uirouter and ngRouter is a one OR the other choice. If you instantiate the controller twice you will have two instances of it.Bipartisan
@Kial : thank you :) its working. I am giving controller in uirouting only and it works :)Lessen
Let me add it as answer so that the question marked answered and I can take some credit :)Kial
K
44

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.

Kial answered 12/9, 2014 at 9:54 Comment(1)
removed ng-controller declaration in html as I have already added it as state setup in router. Things works fine now. Thank you!Shana
H
10

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.

Harpoon answered 11/9, 2014 at 13:14 Comment(3)
@user59442: Your first statement is valid and good for a comment. But your last statement is wrong. This is not an answer.Trichotomy
this helped me for some reasonDead
What does the opinion have to do with the real behavior, those are matters of facts and you should provide an answer based on some kind of concrete factual knowledge, not based on a personal opinion.Jampacked
M
4

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
});
Mweru answered 30/5, 2016 at 11:46 Comment(1)
this helped me.Refrigerator

© 2022 - 2024 — McMap. All rights reserved.