HTML5 Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 150 posts at DZone. You can read more from them at their website. View Full User Profile

Quick Tip: AngularJS Controller Destructor

07.18.2014
| 5469 views |
  • submit to reddit

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 Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)