javascript - $digest 循环后 Angular 如何更新 View ?

标签 javascript angularjs model-view-controller

是否:

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/

相关文章:

javascript - 我应该如何对有很多重叠的代码进行单元测试?

javascript - Angular : Add ngClick from js

java - 为什么 Spring 和 Struts MVC 为其 Controller 类实现单例模式?

java - 对android项目结构和MVC模式感到困惑

javascript - 在 JavaScript 中创建范围 - 奇怪的语法

javascript - 将 dijit.TitlePane 转换为下拉按钮

javascript - 单击处理程序干扰 CSS 悬停状态

javascript - templateURL 的 AngularJS 问题

javascript - 如何模拟 Jasmine 中其他服务方法中调用的 $http.post 方法?

sql - Node JS Sequelize 从 SQL 创建模型