AngularJS ng-app的自動加載與屬性值


ng-app 指令用於告訴 AngularJS 應用當前這個元素是根元素,所有 AngularJS 應用都必須要要一個根元素。


使用ng-app來標記一個DOM結點,在網頁加載完畢時會自動引導(自動初始化)應用程序。

ng-app可以帶屬性值,可以指定加載應用模塊的名稱,ng-app="模塊名稱"。


但是HTML文檔中只允許有一個 ng-app 指令,如果有多個 ng-app 指令,則只有第一個會被使用。

所以想要實現自動加載,那麼就不能讓ng-app帶有屬性值,即不能指定載入應用模塊名稱。


正確寫法

<body ng-app>
    <div ><p> {{ 5 + 5 }}</p> </div>
    <div ><p> {{ 10 + 10 }}</p> </div>
</body>


只加載第一個塊

<body >
    <div ng-app><p> {{ 5 + 5 }}</p> </div>
    <div ng-app><p> {{ 10 + 10 }}</p> </div>
</body>


以下爲ng-app添加屬性值的寫法都是錯誤的,會報錯

<body ng-app=“myApp”>
    <div ><p> {{ 5 + 5 }}</p> </div>
    <div ><p> {{ 10 + 10 }}</p> </div>
</body>


<body >
    <div ng-app=“app1”><p> {{ 5 + 5 }}</p> </div>
    <div ng-app=“app2”><p> {{ 10 + 10 }}</p> </div>
</body>



帶屬性值時候需要手動加載對應ng-app

<body>
    <div id="app1" ng-app="app1">{{ 5 + 5 }}</div>
    <div id="app2" ng-app="app2">{{ 10 + 10 }}</div>
    <script type="text/javascript">
        var app1 = angular.module("app1", []);
        var app2 = angular.module("app2", []);
        angular.bootstrap(document.getElementById("app2"), [ 'app2' ]);
    </script>
</body>

app1會自動加載

app2需要手動加載


angular.bootstrap() ,手動啓動 AngularJS

文檔地址 https://docs.angularjs.org/api/ng/function/angular.bootstrap


angular.bootstrap(element, [modules], [config]);

Arguments

ParamTypeDetails
elementDOMElement      

DOM element which is the root of angular application.

modules

(optional)

Array<String|Function|Array>=      

an array of modules to load into the application.    Each item in the array should be the name of a predefined module or a (DI annotated)    function that will be invoked by the injector as a config block.    See: modules

config

(optional)

Object      

an object for defining configuration options for the application. The    following keys are supported:

  • strictDi - disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. Defaults to false.


element應該對應根ng-app的id,

modules 模塊名數組


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章