范围。$ destroy未触发

时间:2016-11-04 16:34:56

标签: javascript angularjs angularjs-directive angularjs-scope

我创建了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解除绑定事件?

2 个答案:

答案 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)

检查$destroy event

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