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

我怕爱的太早我们不能终老 提交于 2019-12-03 10:52:21

问题


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?


回答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.




回答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.




回答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
});


来源:https://stackoverflow.com/questions/25788032/angular-rootscope-broadcast-event-caught-twice-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!