1

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...!!

Community
  • 1
  • 1
Mr. Noddy
  • 1,530
  • 2
  • 16
  • 45
  • 2
    What is the context of that `$timeout` call? What causes it to execute? – Phil Oct 05 '16 at 08:45
  • Can you post your HTML how you are loading your different controllers ! If you have initiated same controller more than once then this issue is possible. – ngCoder Oct 05 '16 at 09:26
  • Right.... @Angular_10 its happening because of multiple controllers are loaded at some point. I am still looking how this happening... – Mr. Noddy Oct 05 '16 at 09:40
  • Thats why gimme your code let me find that out ! – ngCoder Oct 05 '16 at 09:52
  • Thanks @Angular_10 I have found it finally.... I have header where same controller was used in ng-controller that's why it was registering $scope.$on event multiple times. Issue has been resolved for me now. – Mr. Noddy Oct 05 '16 at 10:36

2 Answers2

1

Quick and dirty hack: use a boolean flag

var once = true;
$timeout(function() {
   if($scope.modal){          
      $rootScope.$broadcast(DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST, {id: id, once: once});
      $scope.modal.hide();
      $scope.modal.remove();
      once = false;
   }
}, 3000);

and in your listener:

$scope.$on(DATAINPUT_EVENT.REFRESH_COMPLETED_DATA_LIST,function(event,args){
   if(args.once)
      // some action, only the first time
});

Bear in mind this is (dirty, but still) solution only if you can't find why your broadcast it's called 3 times every event.

illeb
  • 2,942
  • 1
  • 21
  • 35
  • Thanks @Luxor, this was only happened for that event only so and it was because of controllers I used in my header template. Now its all fine. Problem has been solved now. – Mr. Noddy Oct 05 '16 at 10:37
0

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.

Mr. Noddy
  • 1,530
  • 2
  • 16
  • 45