javascript AngularJS 指令 $document 单击事件每次都会为所有实例触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23426601/
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 $document click event is firing for all instances everytime
提问by shaik
I want to attach an event to the document. when document is clicked I want to remove my directive element. but it is firing for all past instances also.
我想在文档中附加一个事件。单击文档时,我想删除我的指令元素。但它也为过去的所有实例触发。
Below is the code:
下面是代码:
link: function(scope, iElement, iAttrs) {
$document.on('click',function(){
iElement.slideUp('fast',function(){
$(this).remove();
});
});
}
采纳答案by Erik Duindam
When you add jQuery events like this, the event will stay alive even after the directive is destroyed. You have to specifically turn the event off like this:
当您像这样添加 jQuery 事件时,即使指令被销毁,该事件仍将保持活动状态。您必须像这样专门关闭事件:
link: function(scope, iElement, iAttrs) {
$document.on('click',function(){
iElement.slideUp('fast',function(){
$(this).remove();
$document.off('click');
});
});
}
回答by Arun P Johny
Try to remove the handler in the destroy handelr
尝试删除destroyhandelr中的处理程序
link: function (scope, iElement, iAttrs) {
function handler() {
iElement.slideUp('fast', function () {
$(this).remove();
});
}
$document.on('click', handler);
scope.$on('$destroy', function () {
$document.off('click', handler);
})
}