AngularJS digest cycle and watch function

One of the most crucial topics on Angular JS is the working of watch function. We will also take a quick walkthrough on the digest cycle and how it works. So as a pre-requisite before you go though this article, you must have a basic understanding of AngularJS.

Digest cycle

Angular JS defines a concept of digest cycle, which can be considered as a loop, during which AngularJS checks for any changes in the variables that have been marked to be watched. So basically, adding a watch to a variable monitors it through different cycles to check if it’s value has changed. Not all $scope variables should be watched, which it done, the digest loops would take unexpectedly long time to evaluate and would end up running into performance issues. For example, if we have some variable in our controller defined as $scope.testVar and has been marked for being watched, then we are implicitly telling Angular to monitor changes in the testVar in each iteration of the digest cycle. I hope we are clear until now.

So there are two ways to add a watch to any $scope variable –

  1. By using it in your template via expression: <span>{{myVar}}</span>
  2. By adding it manually via $watch service
A very common scenario that you might have definitely comes across in the process of learning Angular JS, but to your knowledge, this sort of expression implants a watch in the background implicitly. Other Angular JS directives such as ng-repeat also do create implicit watches.
$watch service helps to run some code when some value attached to the scope changes. It is not much used, but proves to be helpful sometimes. Later in this article we will be checking out a live example on this approach.

Live Example

In the below example, note how the ‘Save Changes’ button enables and disables itself based on the text box values. Also note that all the text fields are being watched for.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.