AngularJS $digest() Function

Here we will learn $digest() function in angularjs and how to use $scope.$digest() function in angularjs applications to loop through items in watch list with example.

AngularJS $digest() Function

Generally in angularjs whenever we create variables along with $scope object those variables will be added to the watch list.

 

In angularjs $digest() function is a central function of $scope object and it is used to iterate through the watch list items and check if any variable value has been modified or not. In case if any change found in watch list variables then corresponding event listener functions will call and update those values in view with new values.

Syntax of AngularJS $digest() Function

Following is the syntax of using $digest() function in angularjs applications.

 

$scope.$digest();

Example of AngularJS $digest() Function

Following is the example of using $digest() function in angularjs applications.

 

Live Preview

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs $digest() Function with Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script type="text/javascript">

var app = angular.module('digestApp', []);

app.controller('digestCtrl', function ($scope) {

$scope.currentDateTime = new Date();

$scope.updatedtime = function () {

$scope.currentDateTime = new Date();

}

//Added an event listener.

var event = document.getElementById("btndigest");

event.addEventListener('click', function () {

//get dateTime

$scope.currentDateTime = new Date();

//The digest method is use to update date time forcefully.

$scope.$digest();

});

});

</script>

</head>

<body>

<div ng-app="digestApp" ng-controller="digestCtrl">

<h2>AngularJS $digest() Function Example</h2>

<input type="button" value="Click to Update DateTime" ng-click="updatedtime()" />

<input type="button" value="Click to Update DateTime forcefully." id="btndigest" />

<br /><br />

<span style="color : Red">Current Date Time: {{currentDateTime | date:'yyyy-MM-dd HH:mm:ss'}}</span>

</div>

</body>

</html>

If you observe above code we added $scope.$digest() function to update data binding in btndigest event listener click.

 

In case if we remove $scope.$digest() function in btndigest event listener click $scope.currentDateTime variable value will update but that new value will not reflect in view in angularjs applications.

Output of AngularJS $digest() Function

Following is the result of using $digest() function in angularjs applications.

 

Angularjs $digest() function example result or output

 

This is how we can use $digest() function in angularjs applications to loop through watch list items.