Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a scope naturally get destroyed in angularjs lifecycle

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?

like image 611
richbai90 Avatar asked Sep 19 '14 14:09

richbai90


1 Answers

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?

like image 60
bhantol Avatar answered Oct 20 '22 19:10

bhantol