Gaz Smith
Gaz Smith

Reputation: 1108

Angular $destroy is stacking

I have 2 controllers, one has a $destroy function for when the model is closed.

>  $scope.$on("$destroy", function() {
>        
>         var args = {};
>         $rootScope.$emit('refreshh', args);   
>     });

and in the other controller, i have

$rootScope.$on('refreshh', function(event, args) {
        console.log("modal closed");

    });

When i keep opening and closing the model it works fine, i get "modal closed", but then if i go to another page like from the nav bar (without refreshing the page) and go back to that page i will then get "modal closed" "modal closed" and if i repeat this process i will get "modal closed" "modal closed" "modal closed" as if the code is running X amount of times. What could this be?

Upvotes: 2

Views: 41

Answers (1)

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

When you bind an $on listener to $rootScope and you don't explicitly destroy that listener (see docs), then each time your second controller is instantiated, it adds ANOTHER identical listener to $rootScope. In your second controller, you either need to bind to local $scope or be sure to destroy the listener when your second controller is destroyed.

Second controller:

var deregisterListener = $rootScope.$on('refreshh', function(event, args) {
  console.log("modal closed");
});


$scope.$on("destroy", function() {
  deregisterListener();
});

Without this, what ends up happening is that your $rootScope racks up a listener for each time you instantiated your second controller, resulting in all those identical listeners firing at once.

Upvotes: 4

Related Questions