Angularjs – Removing event listeners from a directive in AngularJS

angularjsdomelementeventslistener

I'm trying to realize a simple directive in AngularJS. In particular I want to develop a loader button that change its aspect when pressed, and I want to reuse it in all the page of my application that need it.

I have read on the developer guide that:

"There are a few special events that AngularJS emits. When a DOM node that has been compiled with Angular's compiler is destroyed, it emits a $destroy event. Similarly, when an AngularJS scope is destroyed, it broadcasts a $destroy event to listening scopes. By listening to this event, you can remove event listeners that might cause memory leaks. Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, but if you registered a listener on a service, or registered a listener on a DOM node that isn't being deleted, you'll have to clean it up yourself or you risk introducing a memory leak."

In my link function I have put this code for the event listener:

var onLoaderButtonClickEvent = element.on('click', function(){
//Some stuff

});

Now, have I to consider that as a listener on a DOM element (and so I have to remove it) or not? I'm a lit bit confused.

I think that I have not to remove the listener because is on the "element". Is it correct?

Thx to all

Best Answer

The element.remove() is called automatically when a directive is destroyed, thus removing all listeners on the element. You only have to remove DOM listeners manually if you attached them to any other DOM elements.

From angular's documentation:

Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, but if you registered a listener on a service, or registered a listener on a DOM node that isn't being deleted, you'll have to clean it up yourself or you risk introducing a memory leak.