When I started using ngIf I noticed some
$rootScope event listeners firing more than once per event.
Versions used below
Lifespan of $rootScope vs other scopes
$rootScope lives as long as your app, which is usually the duration of the page. Other scopes are not guaranteed to last that long, like when their directive is nested in ngIf or ngRepeat.
Forgetting to clean up the listener
When a directive like this
is used like this
an event listener will be left behind every time
flag changes from
false. A symptom of this is an event being handled more than once. The extra listeners are sometimes called “zombie” listeners.
Cleaning up the listener
$rootScope.$on() returns a function that will deregister the listener. That function should be invoked when the directive’s scope is destroyed.
With this in mind, the directive changes to