Scope
Scope is one of fundamental building blocks in the Angular1.x framework. Its main purposes are the followings: sharing data, broadcasting and listening events, and watching for changes in data. Poking around the source code of the scope assists me in having a better understanding of what it is going on under the hood. In addition, I will share what I learned from the implementation of the scope in this blog. The scope has five components:
Dirty-Checking Mechanism
Scope Methods
Scope Inheritance
Watching Collections
Scope Events
Dirty-Checking Mechanism
The Angular Scope makes use of two main functions to implement the dirty-checking mechanism: the $watch and $digest function.
$watch(watchFn, ListenFn)
A watch function(watchFn): return the piece of data you’re interested in.
A listen function(listenFn): when the observed data changes, this function will be invoked.
A watcher: an object that has a watch function and a listen function as its attributes.
With $watch you can attach a watcher to a scope. The scope maintains a queue called $$watchers, which stores all the watchers attached to it.
$digest
First, the $digest function iterates all the watchers in the scope.
Second, it compares the previous state of data to the current one during each iteration. If something changes, it calls the corresponding listener function.
Finally, this performs the above steps repeatedly until the watched data stops changing.
Optimization
The Angular Scope takes advantage of the Time To Live(TTL) and short circuiting the digest to avoid endless or useless iterations.
TTL: sets the maximum amount of iterations.
Short-Circuiting: uses a variable to keep track of the last dirty watch that we have seen. Each digest round goes on until it reaches this last watch.
Performance
As I mentioned, Angular Scope iterates over the watches as opposed to the properties of a scope in each digest round. Therefore, it is a good idea to pay attention to the number of watches you have, which will affect the performance of your application.
Top comments (0)