Issue
Suppose a pure AngualrJS (1.6.x) controller declared using ng-controller
directive (in contrary to a component controller).
Does it have lifecycle hooks like $onInit
or $onDestroy
?
Solution
According to the section Scope Life Cycle in the scope documentation (v1.6.10) there are not such hooks (using the ng-controller
approach).
The scope lifecycle would go like this:
- Creation
The root scope is created during the application bootstrap by the $injector
. During template linking, some directives create new child scopes.
- Watcher registration
During template linking, directives register watches on the scope. These watches will be used to propagate model values to the DOM.
- Model mutation
For mutations to be properly observed, you should make them only within the scope.$apply()
. AngularJS APIs do this implicitly, so no extra $apply
call is needed when doing synchronous work in controllers, or asynchronous work with $http
, $timeout
or $interval
services.
- Mutation observation
At the end of $apply
, AngularJS performs a $digest
cycle on the root scope, which then propagates throughout all child scopes. During the $digest
cycle, all $watched
expressions or functions are checked for model mutation and if a mutation is detected, the $watch
listener is called.
- Scope destruction
When child scopes are no longer needed, it is the responsibility of the child scope creator to destroy them via scope.$destroy()
API. This will stop propagation of $digest
calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.
Of course, alternatively, you can always use $rootScope.Scope#$on
for listening for changes.
Examples:
$scope.$on('my-custom-event', function () {
// some code to execute when my-custom-event is fired
});
$scope.$on('$destroy', function () {
// some code to execute when the scope is destroyed
});
Answered By - lealceldeiro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.