Angularjs 指令删除手表? [英] Angularjs directive remove watch?
问题描述
我在指令的控制器中声明了一个 $scope.$watch
.当我更改页面并删除指令时,是否必须手动销毁该方式?如果是这样,我如何检测指令何时被删除?
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?
推荐答案
这取决于作用域,而不是指令.如果范围被破坏,那么它的所有 $watchers 都会随之消亡.在页面更改时,您的范围会被 angular 破坏,所以您应该是安全的.
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.
当一个范围死亡时,它会产生一个 $destroy 事件.你可以看看:
When a scope dies it yields a $destroy event. You can watch it:
$scope.$on('$destroy', callback);
你可以手动从作用域中分离 $watchers,通过调用它返回的函数:
and you can manually detach $watchers from the scope, by calling the function it returns:
var sentinel = $scope.$watch('expression', callback);
sentinel(); // kill sentinel
你也可以用 $on 来做到这一点.
You can do this with $on too.
这篇关于Angularjs 指令删除手表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!