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?
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?
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.
You don't have to write this code.
As per the docs, the $destroy
event is triggered in two cases.
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);
});