Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip: AngularJS Controller Destructor

DZone's Guide to

Quick Tip: AngularJS Controller Destructor

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
css ,html5 ,javascript ,tips and tricks

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}