Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive/controller lifecycle and unbinding $watch and $on listeners

Tags:

angularjs

I'm currently using AngularJS on a project of mine and I am unsure of when/if I need to manually unbind listeners to the $scope (or scope when in the linking function of a directive for example).

From the documentation, which isn't the clearest, I would guess that you do NOT have to unbind to any listeners on the current scope, but I'm not sure whether or not you would have to unbind to listeners on say, the $rootScope for example.

Any clarification about the lifecycle of components such as a directive or a directive's controller would be appreciated.

Thanks

like image 702
Dominic Santos Avatar asked Aug 02 '13 09:08

Dominic Santos


1 Answers

Angular handles that for you.

When scope is destroyed (for example when new view is loaded via ng-view directive old view's scope is destroyed ) all it's child scopes are destroyed and theirs $watchers and listeners registered via $on as well.

$rootScope isn't destroyed at all during lifetime of your application, so you have to manages it's listeners manually, but generally you register there stuff which should be permanent.

When you register listeners via addEventListener you have to remove them manually as it's not managed via angular.

like image 122
Tadeusz Wójcik Avatar answered Sep 21 '22 01:09

Tadeusz Wójcik