I see this type of code a lot in angular modules
scope.$on('$destroy', function(){
//undind listener here
});
My understanding is that whenever the scope is about to be destroyed it broadcasts a $destroy
event allowing you to clean up any code that may continue to run after the destruction of the scope which would create memory leaks.
My question is, when does the scope naturally get destroyed in an angularjs app. All the documentation I can find from the website is that you can manually call $destroy
to remove a scope, but this seems to suggest that it will happen at some point automatically. When would that be?
Scope is tied to HTML elements during compilation. $compile needs a scope to compile an element. Elements could be nested. Some get new scope other inherit.
Scope gets destroyed when elements are removed from DOM.
To be precise: A $destroy
handlers are called on jQuery.cleanData
which AngularJS redefines and calls after it does its cleanup - aka acting in destroying the scope.
cleanData
function is called when an element is removed from the DOM.
What is the purpose of jQuery clean and cleanData methods?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With