为什么在调用 element.remove 时没有触发 $destroy? [英] Why isn't $destroy triggered when I call element.remove?
问题描述
我不明白为什么在下面的例子中没有触发 $destroy 事件.谁能解释一下为什么没有触发,在什么场景下会触发?
I can't figure out why the $destroy event is not triggered in the following example. Can someone explain why it is not triggered, and in what scenarios it will be triggered?
这是 plunkr:http://plnkr.co/edit/3Fz50aNeuculWKJ22iAX?p=preview
angular.module('testMod', [])
.controller('testCtrl', function($scope){
$scope.removeElem = function(id) {
var elem = document.getElementById(id);
angular.element(elem).remove();
}
}).directive('testDir',[function() {
return {
scope:true,
link: function(scope) {
console.log('in directive');
scope.$on('$destroy', function(){
alert('destroyed');
})
}
}
}]);
HTML
<body ng-controller='testCtrl'>
<div testDir id='test'>I will be removed.</div>
<button ng-click='removeElem('test')'>remove</button>
</body>
推荐答案
问题是你监听了 scope
上的 $destroy
事件,但是 $destroy
正在 element
上触发.
The problem is your listening for the $destroy
event on the scope
, but $destroy
is being triggered on the element
.
来自 angular.js 源代码(我确定它在网站上的某个地方有记录,但我没有看):
From angular.js source (I'm sure it's documentated on the website somewhere, but I didn't look):
$destroy
- AngularJS 拦截所有 jqLite/jQuery 的 DOM 销毁apis 并在所有被移除的 DOM 节点上触发这个事件.这个可以用于清除任何 3rd 方绑定到 DOM 元素之前它被删除了.
$destroy
- AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM element before it is removed.
您的指令应该是(请注意,我添加了 scope
、element
和 attrs
作为 link
参数):此外,这是一个 plunker.
Your directive should be (note that I added scope
,element
, and attrs
as link
arguments): Also, here is a plunker.
directive('testDir',[function() {
return {
scope:true,
link: function(scope,element,attrs) {
console.log('in directive');
element.on('$destroy', function(){
alert('destroyed');
})
}
};
}]);
这篇关于为什么在调用 element.remove 时没有触发 $destroy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!