我创建了plunkr demo问题。我在这里面临的问题非常简单:手动调用$ destroy或删除元素并不会触发$ destroy事件。
function link(scope, element, attrs) {
// call scope $destroy, However it doesn't fire the event
scope.$destroy();
// This also won't fire $destroy
element.remove()
scope.$on("$destroy", function handleDestroy() {
console.log("I am destroyed")
})
}
阅读answer之后,我更加困惑。如果element
也获得了$ destroy事件,那么为什么人们在scope
$ destroy而不是element
$ destroy解除绑定事件?
答案 0 :(得分:2)
代码中尚未设置$destroy
事件的回调;所以,在调用scope.$destroy()
所以,它变成了:
function link(scope, element, attrs) {
// this is fired when scope.$destroy() is called
scope.$on("$destroy", function handleDestroy() {
console.log("I am destroyed")
});
//
scope.$destroy();
// this will fire when element.remove() is called
element.on('$destroy', function(){
console.log('elem destroyed');
});
//
element.remove();
}
答案 1 :(得分:0)
app.directive("testDir", function() {
return function(scope) {
scope.$on("$destroy", function() {
console.log("item removed");
});
};
那:angularjs-why-isnt-destroy-triggered-when-i-call-element-remove