Search code examples
angularjscontrollers

$scope.$on fired 3 times


I have 2 different angular controllers and one of it having broadcast like this

$timeout(function() {
    if($scope.modal){
      $rootScope.$broadcast(DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST,id);
      $scope.modal.hide();
      $scope.modal.remove();
    }
}, 3000);

And in another controller I am catching broadcast.

$scope.$on(DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST,function(event,id){
    // some action
});

Problem is $scope.$on function getting called 3 times. I have referred

but could not get solution using them. Please help me out...!!


Solution

  • To fix issue for a moment, I did something like follows,

    if(!$rootScope.$$listenerCount[DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST]){
        $scope.$on(DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST,function(event,id){
             // some action
        });
    }
    

    But very soon I found I have initialized my controller multiple times and I have taken corrective actions to remove the multiple declarations of controller.