Reputation: 197
I have couple of questions about Angular and I would be really thankful if someone clears them up for me.
I understand how scopes work in Angular in case of controllers and directives but I'm confused when are they destroyed (when $destroy is triggered). If someone can throw some light on the life cycle of scopes in Angular it would be just great.
Suppose I have bunch of controllers and directives in my app. When each one of them is loaded and unloaded into the memory. Can someone tell me more about the life cycle of controllers and directives?
Regards.
Upvotes: 2
Views: 2532
Reputation: 123
When a DOM element which was compiled with AngularJS compiler ($compile
) is destroyed it emits a $destroy event, which can be used to remove of directives or controllers, some watchers or event listeners which can cause memory leak.
When a scope is destroyed?
For example, when you change a route with ngRoute, the controller that you was using, have his scope destroyed and loads a new $scope
according to the next route controller.
Another example of when a $scope is destroyed is ngRepeat which destroys the leftover items:
// remove leftover items
for (var blockKey in lastBlockMap) {
block = lastBlockMap[blockKey];
elementsToRemove = getBlockNodes(block.clone);
$animate.leave(elementsToRemove);
if (elementsToRemove[0].parentNode) {
// if the element was not removed yet because of pending animation, mark it as deleted
// so that we can ignore it later
for (index = 0, length = elementsToRemove.length; index < length; index++) {
elementsToRemove[index][NG_REMOVED] = true;
}
}
block.scope.$destroy();
}
How can i destroy a $scope
by myself?
Using the $scope.$destroy();
What happens when a $scope is destroyed?
The Angular emits a $destroy
broadcast event, after that: Disable listeners, watchers and apply/digest methods of that scope, and then execute the default $destroy
event listener which marks the scope as destroyed.
Upvotes: 1
Reputation: 1542
For life cycle of scope, refer the below link
http://onehungrymind.com/notes-on-angularjs-scope-life-cycle/
For life cycle of controller, refer below link
What is the lifecycle of an AngularJS Controller?
Hope it helps...
Upvotes: 0