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

Pratibha picture Pratibha · Sep 11, 2014 · Viewed 14.2k times · Source

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?

Answer

Chandermani picture Chandermani · Sep 12, 2014

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.