Platinum Partner
css,html5,javascript,tips and tricks

Quick Tip: AngularJS Controller Destructor

One of the things you might need to do is to clean up resources when a controller in AngularJS is being deactivated. The way to clean used resources is by listening to the $scope’s $destroy event and when it is triggered to do your clean. In the AngularJS controller lifecycle, a $destroy function is called in order to remove the current scope with all its children from a parent scope. The $destory function is called by AngularJS and once it occurs a $destory event is triggered on the scope. You can use that knowledge and clean resources once the $destory event is triggered.

The following code example shows how to use the $destroy event to remove an event handler that was registered in some pubsubService:

$scope.$on('$destroy', function () {
    pubsubService.off('myEvent');
});

Enjoy.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}