Over a million developers have joined DZone.
Platinum Partner

Quick Tip: AngularJS Controller Destructor

· Web Dev Zone

The Web Dev Zone is brought to you by Stormpath—offering a pre-built Identity API for developers. Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management.

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.

The Web Dev Zone is brought to you by Stormpath—offering a pre-built, streamlined User Management API for building web and mobile applications. Check out our top pointers for designing your REST API.

Topics:
css,html5,javascript,tips and tricks

Published at DZone with permission of Gil Fink , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}