是否:
1) 遍历 DOM(从 ng-app
开始),如果它看到带有指令的 DOM 节点,则使用相应的模型值更新该 DOM 节点。
或
2) 在遍历 $$watchers
列表时,如果它检测到变化,它会引用它需要更新的 DOM 节点,所以它只是这样做(而不是运行通过整个 DOM,使用这种方法,它会存储和使用对 $$watchers
中节点的引用。
最佳答案
更多的是第二种方法。
Angular 通过指令完成所有繁重的工作。您在 Angular 中使用的几乎所有内容都是指令:
<div ng-app>
<div ng-controller>
<button ng-click>
<!-- input is actually a directive -->
<input ng-model="foo" />
所有这些小指令都获得了对它们所附加的 DOM 元素的引用,以及一个 $scope
对象。 这些指令只是注册一个回调,以便在发生变化时执行。
正如您已经注意到的,这些称为观察者。
作用域是分层的,因此总有一个相关对象树构成您的应用程序状态。当 $digest
循环启动时,它会递归遍历树以查找更改,并触发回调(也称为观察者)。
然后回调可以选择做任何它想做的事。只是在大多数情况下,它是在更新 DOM。
归根结底,它的发生过程并没有什么神奇之处。只是一个回调结构,当某些事情发生变化时会执行。
这是一个自定义指令的愚蠢示例,它注册一个观察者并在某些属性发生变化时更新 DOM。
(function(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function updateValue(){
return {
restrict:'A',
link: function(scope, elem, attrs){
elem.on('click', function(){
//You would never actually do this, but
// it's a demo
scope[attrs.updateValue] = "rgb(" +
getRandomInt(0, 255) + "," +
getRandomInt(0, 255) + "," +
getRandomInt(0, 255) + ")";
//kick off a digest loop manually
// this is similar to what a lot of angular
// directives do.
scope.$digest();
});
}
};
}
function sillyDomChangeOn(){
return {
restrict:'A',
link: function(scope, elem, attrs){
scope.$watch(attrs.sillyDomChangeOn, function(newVal, oldVal){
elem.css('color', newVal);
});
}
};
}
angular.module('my-app', [])
.directive('updateValue', updateValue)
.directive('sillyDomChangeOn', sillyDomChangeOn);
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<div ng-app="my-app" class="container">
<button type="button" class="btn btn-primary" update-value="randomVal">Update Value</button>
<h3>Value: <code>{{randomVal}}</code></h3>
<div class="well" silly-dom-change-on="randomVal">
<h3>This is just a random DIV</h3>
<div>
</div>
关于javascript - $digest 循环后 Angular 如何更新 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908800/