1

I have an event on $rootScope in controllerOne:

$rootScope.$on('eventName', function(event, args) {
    invoke function A;    
});

and controllerTwo, I emit the event:

$scope.$emit('eventName', args);

if I first enter the controllerOne, when I emit the event, function A run only one time;and when I enter controllerOne second times, I emit the event and then function A run more than one time, maybe two or three times.

How can I prevent bind event on $rootScope repeatedly

wupeng
  • 63
  • 1
  • 1
  • 10

1 Answers1

4

Use $destroy event to unsubscribe the handler properly: https://stackoverflow.com/a/18856665/4573999

Adapted to your case:

var cleanUp = $rootScope.$on('eventName', function handler(event, args) {
    invoke function A;    
});

$scope.$on('$destroy', function () { 
    cleanUp();
});
Community
  • 1
  • 1
Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38