AngularJs translates re-execution too many times

Inside one of my Angular controllers, I have this:

// controller A $rootScope.$on("myEventFire", function(event, reload) { someAction(); }); 

In another controller, I have the following:

 // controller B $scope.openList = function(page) { $rootScope.$broadcast('myEventFire', 1); } 

Now this is a one-page application. When I first go to controller A and try to fire this event, someAction () will be executed once. If I leave and go back to controller A and do the same, someAction () will execute twice. If I do it again, it will happen three times and so on. What am I doing wrong here?

+45
angularjs angularjs-scope
Oct 23 '13 at
source share
5 answers

Is it possible to use only $scope.$on() ? Each time controller A is created, it adds a new listener to the root area, and this does not get destroyed when navigating back and forth. If you do this in the local area of ​​the controller, the listener should be deleted when you move, and your area will be destroyed.

 // controller A $scope.$on("myEventFire", function(event, reload) { someAction(); }); 

$broadcast sends the event down to all child areas so that it can be found in the local area. $emit works differently, swinging up towards the root space.

+86
Oct 23 '13 at 22:45
source share
β€” -

you can also delete it when the area is destroyed by running the callback from $ rootScope. $ on ().

those.

 var destroyFoo; destroyFoo = $rootScope.$on('foo', function() {}); $scope.$on('$destroy', function() { destroyFoo(); // remove listener. }); 
+22
Jun 19 '14 at 20:42
source share

if you don’t want to destroy,

I think we can check the listener event first - AngularJS 1.2.15

Check Listener Event - Example

So I think this should work:

 if(!$rootScope.$$listenerCount['myEventFire']){ $rootScope.$on("myEventFire", function(event, reload) { someAction(); }); } 
+5
Jun 29 '16 at 6:15
source share

In my case...

 if ($rootScope.$$listenerCount['myEventFire']) { $rootScope.$$listeners.broadcastShowMessageError = []; }; $rootScope.$on('myEventFire', function (event, reload) { someAction(); }) 
0
Jan 11 '17 at 10:28
source share

If this helps anyone, I had a similar problem in the directive. Each time the directive opened the number of times the event was fired, it increased.

I solved this using the following (it was in my controller init function, but I assume that it could be defined in the controller itself. In my case, my controller had to reinitialize when the event was fired)

  if (!$scope.onMyEvent) $scope.onMyEvent= $scope.$on('myEvent',function(event,data){ ..... }); 
0
Aug 16 '17 at 9:32
source share



All Articles