检测指令是否已从 DOM 中删除 [英] Detect if directive was removed from DOM
问题描述
我有一个 AngularJS 指令,如果指令的元素从 DOM 中删除(从 AngularJS 调用内部或通过任何其他方法,如 jQuery),我需要执行某些操作.
I have an AngularJS directive and I need to perform certain actions if the directive's element is removed from the DOM (either from inside an AngularJS call or by any other method, like jQuery).
这可能吗?
推荐答案
在指令中,当一个元素从 DOM 中移除时,会发出 $destroy 事件.在指令的链接函数中,您可以执行以下操作:-
In the directive, when an element is removed from DOM, $destroy event is emitted. Inside your directive's link function, you can do this:-
element.on('$destroy', function() {
// do stuff
});
有关更多信息和完整示例,请参阅文档此处
For more information and complete example, see documentation here
请参阅这个 plunker 以了解 $destroy 的作用.在这里,我在 2 秒后删除元素,并在控制台中销毁日志记录.
See this plunker to see $destroy in action. Here, I am removing the element after 2 seconds, and logging destroyed in console.
这篇关于检测指令是否已从 DOM 中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!