在上節簡單介紹了Angular js架構,在這節將繼續Angular的Bootstrap(引導)和Compiler(編譯)機制。
一:Bootstrap:Angular的初始化
1:Angular推薦的自動化初始如下:
<!doctype html><html xmlns:ng="http://angularjs.org" ng-app><body>...<script src="angular.js"></body></html
利用ngapp標示你需要自動引導應用程式的根節點,一般典型為html tag。在DOMContentLoaded事件觸發Angular會自動尋找ngapp作為應用的根節點,如果找到則會進行如下操作:
1.載入module(模組)相關directive(指令)。
2.建立應用程式injector(Angular的注入機制).
3.編譯處理ng-app作為根節點的指令。這裡允許你自訂選擇DOM節點作為應用根節點。
<!doctype html><html ng-app="optionalModuleName"><body>I can add: {{ + }}.<script src="angular.js"></script></body></html>
2:手動初始化:
如果想對對初始化有更多的控制權,可以採用自訂手動引導方法初始化代替angular的自動初始化。比如你需要在angular編譯模板之前做一些事情,比如改變模板某些內容。手動引導方式將會如下:
<!doctype html><html xmlns:ng="http://angularjs.org"><body>Hello {{'World'}}!<script src="http://code.angularjs.org/angular.js"></script><script>angular.element(document).ready(function() {angular.bootstrap(document);});</script></body></html>
1.在頁面所有代碼載入完成後,找到html模板根節點(典型為document元素).
2.調用api/angular.bootstrap(angular.bootstrap(element[, modules]))編譯模板使其可執行.
二:Compiler:Angular的編譯
Angular的編譯機制允許開發人員給瀏覽器添加新的Html文法,允許我們添加一些html節點,attribute,甚至建立一些自訂的節點,attribute。Angular把這些行為的擴充成為指令directives.Angular帶來了有用的directive,並允許我們建立特定領域的directive。
1: Compiler處理分為兩個步驟:
1.轉換DOM,收集directive,返回Link(串連)function。
2.合并指令和Scope產生一個活生生的View。scop mode中的任何改變都會通過反應到view中,並來自view的使用者互動也會同步到scope model,並scope是一個單一資料來源。
2:指令Directive
Directive是一個會被特殊的html設計編輯處理的行為。其可以被放置在節點的names, attributes, class 上,甚至是html注釋中。下面是Angular內建的ng-bind的等價寫法:
<span ng-bind="exp"></span><span class="ng-bind: exp;"></span><ng-bind></ng-bind><!-- directive: ng-bind exp –>
directive僅僅是一個在dom中會被Angular執行的一個function。下面是一個拖拽的執行個體,其可以被應用於span,div的attribute上:
angular.module('drag', []).directive('draggable', function ($document) { var startX = , startY = , x = , y = ; return function (scope, element, attr) { element.css({ position: 'relative', border: 'px solid red', backgroundColor: 'lightgrey', cursor: 'pointer' }); element.bind('mousedown', function (event) { startX = event.screenX - x; startY = event.screenY - y; $document.bind('mousemove', mousemove); $document.bind('mouseup', mouseup); }); function mousemove(event) { y = event.screenY - startY; x = event.screenX - startX; element.css({ top: y + 'px', left: x + 'px' }); } function mouseup() { $document.unbind('mousemove', mousemove); $document.unbind('mouseup', mouseup); } } });
Demo
you can drag and move me to anywhere !
3:view理解
有許多的模板引擎都被設計為模板(template)和資料(model)的合并返回一個字串,再利用innerHTML追加在DOM節點,這以為則資料的任何改變都必須重新合并產生新的內容追加在DOM上。形如下圖屬於單向綁定技術:
而Angular則不同利用directive指令而非字串,傳回值是一個合并資料model的link function。view和model的綁定是自動,透明的,不需要開發人員添加額外的action去更新view,Angular在這裡不僅是資料model的綁定,還有行為概念。作為雙向的綁定,形如下圖:
資料:
1.Angular官網:http://angularjs.org/
2.代碼下載:https://github.com/angular/angular.js
以上所述是小編給大家介紹的Angular的Bootstrap(引導)和Compiler(編譯)機制,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!