DIV CSS 佈局教程網

AngularJS 入門導引:從手動啟動到編譯器與自訂指令
編輯:關於JavaScript     

關於這篇筆記該寫給誰看、又該從哪裡落筆,我其實猶豫了很久。最後決定不做過多鋪墊,直接從一條最清晰的主線切進去:先搞懂 AngularJS 的啟動機制,再看懂它的編譯器,最後動手寫一個屬於自己的 directive。

一、angular.element 與 angular.bootstrap

我們都知道,只要在頁面中加入 ng-app,Angular 就會自動替我們完成初始化。這個過程大致可以拆成四步:

  1. 在 document 觸發 load 時,Angular 會先找到 ng-app 指令所標記的節點;
  2. 載入與該 module 相關的指令;
  3. 建立與應用關聯的 injector(依賴注入容器);
  4. 以 ng-app 所在節點為根,開始對 DOM 進行 compile。

既然如此,我們完全可以跳過 ng-app,自己動手做一遍等價的事情。這裡要用到兩個 API:angular.element 負責包裝,它能像 jQuery 一樣把原生 DOM 元素或 HTML 字串包成 jQuery 物件;angular.bootstrap 則用來手動完成啟動。

示例程式碼:

<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Bootstrap-manual</title>
<style type="text/css">
.ng-cloak {
display: none;
}
</style>
</head>
<body>
這裡是ng-app外面的~~{{1+2}}
<div id="widuu" >這裡是ng-app裡面~~~ {{1+2}}</div>
<script src="angular.min.js" type="text/javascript"></script>
<script type="text/javascript">
angular.element(document).ready(function() {
angular.bootstrap(angular.element(document.getElementById("widuu")));
});
</script>
</body>
</html>

執行後你會發現,只有 widuu 這個節點裡的插值被解析,外面的 {{1+2}} 依舊原樣輸出——這正好印證了「bootstrap 的作用範圍就是傳入的那個節點」。

二、compiler:Angular 的 DOM 編譯器

翻閱 AngularJS 官方文件時會發現,指令一律採用駝峰式命名,例如 ngApp、ngModule、ngBind。HTML compiler 的職責,就是允許我們自訂元素、屬性與標籤,Angular 把這些附加行為統稱為 directives。

官方對 compiler 的描述如下:

Compiler is an Angular service which traverses the DOM looking for attributes. The compilation process happens in two phases.

Compile: traverse the DOM and collect all of the directives. The result is a linking function.

Link: combine the directives with a scope and produce a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model. This makes the scope model the single source of truth.

Some directives such as ng-repeat clone DOM elements once for each item in a collection. Having a compile and link phase improves performance since the cloned template only needs to be compiled once, and then linked once for each clone instance.

用白話整理一遍:compiler 是 Angular 的一個 service,負責遍歷 DOM 節點並查找屬性,整個編譯過程分成兩個階段。

編譯(Compile):遍歷節點、收集所有 directives,最終返回一個連結函數(linking function)。

連結(Link):把收集到的 directives 綁定到某個 scope 上,產生出可互動的實況視圖(live view)。scope 中的任何變動都會反映到視圖上;反過來,使用者在視圖上的操作也會回寫到 scope model。雙向同步讓 scope 成為唯一的資料來源。

像 ng-repeat 這類指令,會為集合中的每個項目複製一份 DOM。把流程拆成 compile 與 link 兩段的好處就在於:樣板只需要編譯一次,之後每個複本各自連結即可,性能因此明顯提升(有點接近樣板快取的效果)。

三、一步步打造自己的 directive

1. 先認識 directive 的命名規則

directive 採用駝峰式命名(如 ngModule),編譯時的匹配規則如下:

<input ng-model="foo">
<input data-ng:model="foo">

也就是說,directive 可以加上 x- 或 data- 前綴,並可用 :、-、_ 等分隔符來對應駝峰寫法:

<span ng-bind="name"></span> <br/>
<span ng:bind="name"></span> <br/>
<span ng_bind="name"></span> <br/>
<span data-ng-bind="name"></span> <br/>
<span x-ng-bind="name"></span> <br/>

日常開發中最常見的還是 ng-bind 對應 ngBind 這種形式。此外,$compile 還能依據元素名稱、屬性、類名甚至註解來匹配 directive:

<my-dir></my-dir>
<span my-dir="exp"></span>
<!-- directive: my-dir exp -->
<span class="my-dir: exp;"></span>

編譯過程中,compiler 會透過 $interpolate 服務去比對文字與屬性中的插值表達式(例如 {{something}})。這些表達式會被註冊成 watches,並在 digest cycle 中一起更新。一個最簡單的插值例子:

<img src="img/{{username}}.jpg"/>Hello {{username}}!

2. 編譯的三個步驟

第一步:把 HTML 轉成 DOM。透過瀏覽器標準 API 將 HTML 字串解析為 DOM 物件。這一步至關重要,因為樣板必須是合法可解析的 HTML。這也是 Angular 與多數「基於字串」的樣板系統最大的差異所在。

第二步:呼叫 $compile() 完成編譯。該方法會遍歷 DOM 並嘗試匹配 directive,匹配成功就把 directive 與對應 DOM 一起收進列表。當某個 DOM 關聯的所有 directive 都被辨識出來後,它們會依優先級排序,並按此順序執行各自的 compile()。directive 的編譯函數有機會修改 DOM 結構,並負責產生出 link 函數。$compile() 最終回傳的,是所有 directive 自身 link 函數的集合。

第三步:把樣板與 scope 連結起來。呼叫上一步得到的 linking function,它會反向觸發各 directive 的 link 函數,讓它們在元素上註冊監聽器、建立 watches。結果就是 scope 與 DOM 之間形成雙向即時綁定:scope 一變,DOM 立刻響應。

var $compile = ...; // injected into your code
var scope = ...;
var html = '<div ng-bind="exp"></div>';

// Step 1: parse HTML into DOM element
var template = angular.element(html);

// Step 2: compile the template
var linkFn = $compile(template);

// Step 3: link the compiled template with the scope.
linkFn(scope);

3. ngAttr 屬性綁定

有些屬性(特別是 SVG 相關的)原生 DOM 並不認識,這時需要用 ng-attr- 前綴來綁定:

<svg>
<circle ng-attr-cx="{{cx}}"></circle>
</svg>

今天先整理到這裡。下一篇開始動手實作自訂 directive,概念鋪墊得差不多,剩下的就交給練習了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved