If you angular $apply, $digest, $watch indefinitely, then I believe that the following words can make you understand deeply!
This article is aimed at the students who have known $apply, $digest, $watch. That is to say you have searched many blog forums for $apply, $digest, $watch, though somewhat masked, but indefinitely feeling.
If you have never been to the understanding, then this article will not help you a little!
<!DOCTYPE html>
<html lang="zh-CN" ng-app="app">
<head>
<meta charset="utf-8">
< title > angular clock assisted understanding $apply, $digest, $watch < / Title >
<link rel="stylesheet" href="../bootstrap.min.css">
</head>
<body ng-controller="myController">
<div ng-bind="clock.now"></div>
<script src="../angular.min.js"></script>
<script>
angular.module(‘app‘, [])
.controller(‘myController‘, function($scope, $timeout, $interval) {
/ / the first kind
// $scope.clock = {};
// var clockFunction = function() {
// $scope.clock.now = new Date();
//$timeout (function() {/ / use $timeout instead of settimeout(), because the former has already called $apply()
// clockFunction();
// }, 1000)
// // setTimeout(function() {
// // $scope.$apply(clockFunction);
// // }, 1000)
/ /}
// clockFunction();
/ / second kinds
$scope.clock = {
now: new Date()
}
var updateClock = function() {
$scope.clock.now = new Date();
}
Setinterval (function() {/ / if you do not use $interval, you need to call $apply() manually to update the changed $scope to view in time
$scope.$apply(updateClock);
//It can be seen that $scope has changed but not updated to view in time
// updateClock();
// console.log($scope.clock.now);
}, 1000);
updateClock();
}
</script>
</body>
</html>
Get ready to start!
$APPLY (Notification)
$digest (circular)
$watch (Listening)
There may be differences in English translation, but this is not the point, the point is to make you understand
Angular is sure to do when listening for data changes and performing two-way binding:
Notification ($apply) angular tells him that there is a function test ($apply test) that requires him to help with a dirty check ($digest dirty check), monitor the data changes ($watch) while doing a dirty check, and reflect in view
When not in the angular context, you need to manually $apply. If you do not do $apply although angular can monitor data changes, he does not update the data to view in time because he doesn't know when your data is up to date.
Thank you for reading, I hope to help you, thank you for your support for this site!