javascript Angularjs 指令删除手表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16956004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs directive remove watch?
提问by Harry
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?
我$scope.$watch
在指令的控制器中声明了一个。当我更改页面并删除指令时,是否必须手动销毁该方式?如果是这样,我如何检测指令何时被删除?
回答by Oliver
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.
这取决于范围,而不是指令。如果范围被破坏,那么它的所有 $watchers 都会随之消亡。在页面更改时,您的范围将被 angular 破坏,因此您应该是安全的。
When a scope dies it yields a $destroy event. You can watch it:
当范围死亡时,它会产生一个 $destroy 事件。你可以观看:
$scope.$on('$destroy', callback);
and you can manually detach $watchers from the scope, by calling the function it returns:
并且您可以通过调用它返回的函数来手动从作用域中分离 $watchers:
var sentinel = $scope.$watch('expression', callback);
sentinel(); // kill sentinel
You can do this with $on too.
你也可以用 $on 做到这一点。