標籤:
angularjs 是個神奇的架構,由於我的好奇,想瞭解她的內部工作原理,只能一步一步的走進她,靠近她,和她深入的交流。
angularjs 的入口是什麼樣子的呢?一起掀起她的蓋頭吧。
在這裡我只講方法,具體的行號不做記錄,自己找吧(Ctrl+F);
入口是這樣的:
jqLite(document).ready(function() { angularInit(document, bootstrap);});
原理簡單,就是擷取document ready 結束時,調用angularInit(document, bootstrap); 我們今天的重頭戲是angularInit()方法, 暫時不講bootstrap。
1 var ngAttrPrefixes = [‘ng-‘, ‘data-ng-‘, ‘ng:‘, ‘x-ng-‘]; 2 function angularInit(element, bootstrap) { 3 var appElement, 4 module, 5 config = {}; 6 7 // The element `element` has priority over any other element 8 forEach(ngAttrPrefixes, function(prefix) { 9 var name = prefix + ‘app‘;10 11 if (!appElement && element.hasAttribute && element.hasAttribute(name)) {12 appElement = element;13 module = element.getAttribute(name);14 }15 });16 forEach(ngAttrPrefixes, function(prefix) {17 var name = prefix + ‘app‘;18 var candidate;19 20 if (!appElement && (candidate = element.querySelector(‘[‘ + name.replace(‘:‘, ‘\\:‘) + ‘]‘))) {21 appElement = candidate;22 module = candidate.getAttribute(name);23 }24 });25 if (appElement) {26 config.strictDi = getNgAttribute(appElement, "strict-di") !== null;27 bootstrap(appElement, module ? [module] : [], config);28 }29 }
這個方法就是angularjs 擷取ng-app ([‘ng-‘, ‘data-ng-‘, ‘ng:‘, ‘x-ng-‘] app有這幾種寫法)的方法, 8~24行都是為了尋找整個頁面中的app屬性,此時只會擷取第一個帶有app的屬性元素,這也是為什麼一個程式中只能有一個app的原因,如果找到了帶有app的屬性,就執行26~27行代碼,如果沒有找到,對不起,angularjs 沒有了卵用,這就為什麼必須剛開始寫ng-app="XXXX"。
那麼26行是什麼意思呢?
1 function getNgAttribute(element, ngAttr) { 2 var attr, i, ii = ngAttrPrefixes.length; 3 for (i = 0; i < ii; ++i) { 4 attr = ngAttrPrefixes[i] + ngAttr; 5 if (isString(attr = element.getAttribute(attr))) { 6 return attr; 7 } 8 } 9 return null;10 }
就是判斷 是strict 模式嗎,即在app的元素上 寫ng-strict-di屬性了嗎,當找到了就返回擷取的屬性值,沒有找到就返回null;
你可能有疑惑什麼是strict 模式,自己看看吧,https://docs.angularjs.org/api/ng/directive/ngApp 搜搜“ ngStrictDi ”,自己可以試試。
執行完getNgAttribute() 返回的值進行判斷後 賦給了config.strictDi(true/false)。
好了,先講這些吧,下次講講bootstrap()方法
angular 源碼分析 1 - angularInit()