misaizdaleka misaizdaleka - 3 months ago 7
AngularJS Question

AngularJs broadcast repeating execution too many times

Inside one of my Angular controllers, I have this:

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

In another controller I have this:

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

Now, this is a single-page app. When I go to controller A initially and try triggering this event, someAction() is going to be executed once. If I navigate away and come back again to controller A and do the same thing, someAction() gets executed twice. If I do it again, it happens three times and so on.
What am I doing wrong here?


Can you try just using $scope.$on()? Every time controller A is created, it is adding a new listener on the root scope, and that doesn't get destroyed when you navigate away and back. If you do it on the controller's local scope, the listener should get removed when you navigate away and your scope gets destroyed.

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

$broadcast sends the event downward to all child scopes so it should be picked up on your local scope. $emit works the other way bubbling up towards the root scope.