Angularjs directive remove watch?

本秂侑毒 提交于 2020-01-13 09:15:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16956004/angularjs-directive-remove-watch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!