I’ve been doing some reading up on AngularJS today to refresh my understanding of how it works. Today I was looking at Scope, here’s my notes on what I found out:
Scope has a lifecycle made up of 5 stages
- Creation – when the root scope is created during the application bootstrap by the $injector service. During this process template linking takes part. Directives create child scopes.
- Watcher registration – $watches are setup and used to propagate the model values to the DOM.
- Model mutation – model mutation only happens when $apply is need when doing asynchronous work in controllers, or async work with services, like $http.
- Mutation Observation – At the end of the $apply stage, Angular performs a $digest cycle on the root scope, which then goes through all the child scopes. During this stage all the $watches expressions or functions are checked for changes to the model and if a change has been detected, the $watch listener is called.
- Scope destruction – When a child scope is no longer needed it needs to be destroyed. This is the responsibility of the child scope creator to do this using scope.$destroy(). This stops any propagation of $digest calls into the child scope and allow for the garbage collector to reclaim the memory.
So the way I see Angular works is, when your app starts the ng-app is a directive, and everything within that is then accessible to the Angular compiler which goes through the DOM and collects all the directives within the app. Then links all directives with a scope object to produce a live view of the model in these views. All this compilation is done in the browser unlike other templating systems that do this before rendering in the browser.
Once all these directives and scopes are linked, a series of $watches are setup all watching the expressions and functions within the scope(s). Any changes trigger the $watcher function, these $watch functions are triggered as part of the $digest cycle. When the $digest cycle starts it fires each of the watcher functions, which check to see if there is a different with the current model from the previous version of the model.
This is a great article on understanding Apply and Digest
There is still a lot more to Angular which I’m going still got to look into in further details. And how Angular 1.5 and it’s a new component structure effect how the scope and digest cycle works.
Any feedback on this would be really helpful