$digest in AngularJs

What is $digest method in Angular?

The angular $digest is a scope method. It is called scope object and It use to update the model properties forcefully and its use to allow to manually trigger.

Syntax:  $scope.$digest();

How to call $digest() method?
The angularjs digest method is call using the scope i.e. $scope.$digest();

The below example is explain about how to use the $digest(). Please see and understand in detail.
//The AngularJs code
var app = angular.module("myApp", []);
app.controller("myCtrl", ["$scope", function ($scope) {
            //set default datetime.
            $scope.currentDateTime = new Date();

            //update datetime.
            $scope.getUpdatedDateTime = function () {
                $scope.currentDateTime = new Date();
            }

//Added an event listener.
var event = document.getElementById("btnAppyToDigest");
event.addEventListener('click', function () {
                //get dateTime
                $scope.currentDateTime = new Date();

                //The digest method is use to update date time forcefully.
                $scope.$digest();
            });
}]);

//The Full Live (AngularJs + HTML) code sample
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>AngularJs digest method</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var app = angular.module("myApp", []);

        app.controller("myCtrl", ["$scope", function ($scope) {
            //set default datetime.
            $scope.currentDateTime = new Date();

            //update datetime.
            $scope.getUpdatedDateTime = function () {
                $scope.currentDateTime = new Date();
            }

            //Added an event listener.
            var event = document.getElementById("btnAppyToDigest");

            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 ng-app="myApp" ng-controller="myCtrl">
    <h2>AngularJs digest method</h2>
    <div>
        <div>
            <button ng-click="getUpdatedDateTime()">Click to Update DateTime</button>
            <button id="btnAppyToDigest">Click to Update DateTime forcefully.</button>
        </div>
        <div>Result : {{currentDateTime | date:'MM-dd-yyyy HH:mm:ss'}}</div>
    </div>
</body>
</html>

The live Output,

About Blogger

ANIL SINGH

Hey! I am Anil Singh. I am Active Blogger, Writer and Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book