AngularJS two way data binding


Angular has some magic under its hood. it enables binding DOM to real js variables.

Angular uses a loop, named the "digest loop", which is called after any change of a variable - calling callbacks which update the DOM.

For example, the ng-model directive attaches a keyup eventListener to this input:

<input ng-model="variable" />

Every time the keyup event fires, the digest loop starts.

At some point, the digest loop iterates over a callback which updates the contents of this span:


The basic life-cycle of this example, summarizes (very Schematically) how angular works::

  1. Angular scans html
    • ng-model directive creates a keyup listener on input
    • expression inside span adds a callback to digest cycle
  2. User interacts with input
    • keyup listener starts digest cycle
    • digest cycle calles the callback
    • Callback updates span's contents