簡體   English   中英

Angular如何在$摘要周期后更新視圖?

[英]How does Angular update the view after a $digest cycle?

可以:

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM