Questions And Answers

More Tutorials

Angular digest loop walkthrough

$digest and $watch

Implementing two-way-data-binding, to achieve the result from the previous example, could be done with two core functions:

.$digest is called after a user interaction (binding DOM=>variable)
.$watch sets a callback to be called after variable changes (binding variable=>DOM)

note: this is example is a demonstration, not the actual angular code

<input id="input"/>
<span id="span"></span>

The two functions we need:

var $watches = [];
function $digest(){
 var val = $w.val();
 if($w.prevVal !== val){
 $w.callback(val, $w.prevVal);
 $w.prevVal = val;
function $watch(val, callback){
 $watches.push({val:val, callback:callback, prevVal: val() })

Now we could now use these functions to hook up a variable to the DOM (angular comes with built-in directives which will do this for you):

var realVar; 
//this is usually done by ng-model directive
}, true);
//this is usually done with {{expressions}} or ng-bind directive
$watch(function(){return realVar},function(val){
 span1.innerHTML = val;

Off-course, the real implementations are more complex, and support parameters such as which element to bind
to, and what variable to use


In this page (written and validated by ) you learned about AngularJS digest loop walkthrough . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS the scope tree.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.