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

前端 未结 3 1009
醉梦人生
醉梦人生 2021-02-05 04:27

Broadcating event on button click :-

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

And catching event in

相关标签:
3条回答
  • 2021-02-05 05:07

    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.

    0 讨论(0)
  • 2021-02-05 05:08

    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
    });
    
    0 讨论(0)
  • 2021-02-05 05:14

    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.

    0 讨论(0)
提交回复
热议问题