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.