3

Found this code one of the directives in a project I'm working on:

element.on('$destroy', function () {
    scope.$destroy();
});

Is this code needed? Or can I remove it? Isn't scope destroyed when directive is destroyed?

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • I was using something like that when worked on a subcomponent for a website, some of the elements were removed by parent application outside of our angular app and that was only way to destroy some bindings and listeners – maurycy Jan 24 '17 at 15:56
  • The only point I see - if this is scope of another element. This is still sh**, but may do something. – Petr Averyanov Jan 24 '17 at 16:33
  • the code was calling compile/append of another directive, but I've remove it. – jcubic Jan 25 '17 at 09:44

2 Answers2

1

Keep that there unless you identify it's purpose, $destroy() actually removes the scope from its parent scope, below is the excerpt of official documentation

$destroy(); Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

Also Please check this SO Thread for example and detailed explanation.

Community
  • 1
  • 1
Jeet
  • 5,569
  • 8
  • 43
  • 75
1

You don't have to write this code.

As per the docs, the $destroy event is triggered in two cases.

  • Just before a scope is destroyed
  • Just before an element is removed from the DOM

As a side note, you can still use the scope of the element in the element.on('$destroy') event before the scope will be destroyed:

element.on('$destroy', function() {
    console.log('RIP', scope);
});
Mistalis
  • 17,793
  • 13
  • 73
  • 97