SoFunction
Updated on 2025-04-13

Detailed explanation of $apply, $digest, $watch in angularjs

If you don’t understand angular’s ​​$apply, $digest, and $watch, then I believe the following sentences will give you a deep understanding!

This article is for students who have already learned about $apply, $digest, and $watch. In other words, you have searched for $apply, $digest, and $watch on many blog forums. Although it is a bit confusing, it feels like it is not clear.

If you have never learned about it, this article will not help you at all!

<!DOCTYPE html>
<html lang="zh-CN" ng-app="app">
<head>
  <meta charset="utf-8">
  <title>angularClock assisted understanding$apply,$digest,$watch</title>
  <link rel="stylesheet" href="../">
</head>
<body ng-controller="myController">

  <div ng-bind=""></div>


  <script src="../"></script>
  <script>
    (‘app‘, [])
    .controller(‘myController‘, function($scope, $timeout, $interval) {

      // The first type      // $ = {};
      // var clockFunction = function() {
      //   $ = new Date();
      // $timeout(function() { // Use $timeout instead of setTimeout(), because the former has called $apply()      //     clockFunction();
      //   }, 1000)
      //   // setTimeout(function() {
      //   //   $scope.$apply(clockFunction);
      //   // }, 1000)
      // }
      // clockFunction();

      // The second type      $ = {
         now: new Date()
      };   
      var updateClock = function() {
        $ = new Date();
      };   
      setInterval(function() { // If you do not use $interval, you need to call $apply() manually to make the changed $scope update to the view in a timely manner        $scope.$apply(updateClock);

        // Here we can see that $scope has changed but has not been updated to the view in time        // updateClock();
        // ($);
      }, 1000);   
      updateClock();
    })
  </script>
</body>
</html>

Ready to start!

$apply (notification)
$digest (loop)
$watch (listening)

There may be some difference here with English translation, but this is not the point, the point is to make you understand

What angular will do when listening for data changes and performing two-way binding:

Notify ($apply) angular, tell him that there is a function test ($apply(test)), and he needs his help to do dirty checks ($digest dirty checks), and listen to data changes ($watch) while doing dirty checks and reflect them in the view.

When not in the angular context, you need to manually $apply. If you don't do $apply, although angular can monitor data changes, it will not update the data to the view in time, because it does not know when your data is latest

Thank you for reading, I hope it can help you. Thank you for your support for this site!