I have a $scope.$watch
declared in the controller of a directive. When I change pages and the directive is removed do I have to manually destroy the way? If so how do I detect when the directive has been removed?
Asked
Active
Viewed 1.1k times
7

Harry
- 52,711
- 71
- 177
- 261
-
Angular should take care of that for you – gion_13 Jun 06 '13 at 07:27
1 Answers
21
It depends on the scope, not the directive. If the scope is destroyed, then all its $watchers die with it. On page change your scope'll be destroyed by angular, so you should be safe.
When a scope dies it yields a $destroy event. You can watch it:
$scope.$on('$destroy', callback);
and you can manually detach $watchers from the scope, by calling the function it returns:
var sentinel = $scope.$watch('expression', callback);
sentinel(); // kill sentinel
You can do this with $on too.

Oliver
- 4,471
- 2
- 21
- 18
-
Firstly, you said when scope is destroyed, all watchers die with it. Then you suggested manually removing watchers on scope $destroy event (why? they are supposed to automatically die with scope). That does not make sense to me. Could you elaborate please? – hendrix Apr 24 '14 at 10:36
-
2When the page is changed with the ngView angular will cleanup the last scope for you with the watchers. (proof => http://goo.gl/GD0pM9) Also angular gives you a watcher destroy function so you can manually remove the expression if you don't need it anymore on the current scope. – Oliver Apr 25 '14 at 13:43