How does AngularJS know when variables change? How does AngularJS dirty checking work?
Solution 1:
From this link:
Angular defines a concept of a so called digest cycle. This cycle can be considered as a loop, during which Angular checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are explicitly telling Angular to monitor the changes on myVar in each iteration of the loop.
This "digest
" is also called "dirty checking", because, in a way, it scans the scope for changes. I cannot say if it's for better or for worse than observable pattern. It depends on your needs.
Some links:
- Angular documentation
- A blog post about Angular scopes
Solution 2:
Angular Dirty Checking mechanism workflow.
Dirty checking is a simple process that boils down to a very basic concept: It checks whether a value has changed that hasn’t yet been synchronized across the app.
Our Angular app keeps track of the values of the current watches. Angular walks down the $watch list, and, if the updated value has not changed from the old value, it continues down the list. If the value has changed, the app records the new value and continues down the $watch list.
Check out the whole article here
Solution 3:
What is dirty checking?
The process of checking every watch to detect the changes, is called dirty checking. There could be two scenarios
First –
- Get a watch from list
- Check whether item has been changed
- If there is no change in item then
- No Action taken, move to next item in watch list
Second–
- Get a watch from list
- Check whether item has been changed
- If there is Change in an item
- DOM needs to be updated, return to digest loop
In second case, loop continues till it finds no changes in the entire loop. And once it completes, DOM gets updated if required.