2016-05-20 50 views
15

我正在通過angularJS的基本知識介紹它是如何手動引導的。我遇到了不同的方法,發現this approach是最合適的。瞭解angularJS的步驟明智的手動引導

angular.element(document).ready(function(){ 
    angular.bootstrap(document,['myapp']) 
}) 

繼續前進,我碰到了this another way which breaks it to basics。根據我的理解,我已經評論了代碼,但是有人可以向我詳細解釋一下情況如何。

window.onload = function(){ 

    var $rootElement = angular.element(window.document); 
    var modules = [ 
    'ng',  // angular module 
    'myApp', // custom module 
    // what are we trying to achieve here? 
    function($provide){ 
     $provide.value('$rootElement',$rootElement) 
    } 
    ]; 

    var $injector = angular.injector(modules);  // one injector per application 
    var $compile = $injector.get('$compile');  // Compile Service: it traverses the DOM and look for directives and compile and return linking function. No accecess to scope 
    var compositeLinkFn = $compile($rootElement); // collection of all linking function. Here scope is getting accessed 

    var $rootScope = $injector.get('$rootScope'); // Hold of the rootscope 
    compositeLinkFn($rootScope); 

    $rootScope.$apply(); 
} 

另外,請隨時通過提出更多的方法和改進來啓發我更多關於此主題。

+0

我想也許你的問題是過於寬泛。你有什麼機會縮小它? – hkBst

+0

@hkBst:不知道該怎麼辦這個問題。我想了解發生了什麼,我已經提供了所有步驟。這是我一直保持這種恩惠:( –

回答

10

我們試圖在這裏實現什麼?

var modules = [ 
    'ng',  // angular module 
    'myApp', // custom module 
    function($provide){ 
     $provide.value('$rootElement',$rootElement) 
    } 
    ]; 

也就是老一套依賴注入我們angularjs到處使用。 我們在這裏注入模塊ng並註冊一個value

最後,我們通過它在angular.injector()

var $injector = angular.injector(modules) 

還是不相信?下面是簡單的版本

var $injector = angular.injector(['ng','myApp',function($provide){ 
    $provide.value('$rootElement',$rootElement) 
}]) 

現在兩個問題,

  1. 我們爲什麼要使用angular.injector(我們使用的控制器DI的方式)?

    因爲,angular.injector創建一個注入器對象,可用於檢索服務以及依賴注入。我們需要獲得$ compile服務和範圍的實例以將該模板綁定到。

  2. 我們爲什麼要設置$rootElement

    讓角度知道應用程序的根元素。注意到在angular.bootstrap(document,['myapp'])中使用document?這是出於同樣的原因。

    按照official documentation of $rootElement

    $ rootElement的要麼是地方ngApp被宣佈爲元素或傳遞到angular.bootstrap的 元素。

    由於我們既沒有使用ng-app也沒有使用標準的angular.bootstrap方法,所以我們必須手動設置它。

接下來,我們嘗試從我們剛剛從上述步驟收到的注入器實例獲取$compile服務。

var $compile = $injector.get('$compile'); 

$ compile服務是用於編譯的服務。調用$編譯針對標記會產生一種功能,你可以用它來標記綁定針對特定範圍(什麼角度調用鏈接功能)

再次拿到範圍,我們使用$injector.get('$rootScope'),並把它傳遞複合鏈接函數,我們從$編譯。

angular.bootstrap(document,[myApp])只是上述步驟中的一個語法糖。它創建一個注入器實例,在其幫助下設置相關服務,創建應用程序範圍並最終編譯模板。

這從official documentation for angular.bootstrap明顯可見,它清楚地提到它返回一個噴射器實例。

汽車。$注射返回新創建的噴油器爲這個應用程序

同樣的故事在official bootstrap guide

說明指出,我們提供我們的應用程序模塊的名稱將 裝入噴射器作爲angular.bootstrap的第二個參數 功能請注意,angular.bootstrap不會在 飛行中創建模塊。您必須創建任何自定義模塊,然後將其作爲參數 傳遞。

最後,不用say..all這有裝載的HTML文檔之後進行和DOM已準備就緒。

編輯

下面是這個過程的示意圖。 angular.bootstrap process http://www.dotnet-tricks.com/Content/images/angularjs/bootstrap.png Image Reference

希望它能幫助:)

+0

這是非常有幫助的。謝謝:) –