?
Ce document utilise Manuel du site Web PHP chinois Libérer
使用這個指令自動載入啟動一個AngularJS應(yīng)用。 ngApp
指令設(shè)計為應(yīng)用的根元素,一般把它放在頁面的根元素附近,例如<body>
或<html>
標(biāo)簽。
每個HTML文檔只有一個AngularJS應(yīng)用能被自動載入啟動。文檔中找到的第一個ngApp
將被用于定義自動載入啟動的應(yīng)用的根元素。要在一個HTML文檔中運行多個應(yīng)用,你必須使用angular.bootstrap
來手工啟動。AngularJS應(yīng)用間不能嵌套。
你能指定一個 AngularJS module 作為應(yīng)用的根模塊。當(dāng)應(yīng)用被啟動后,這個模塊將被載入到$injector
,并且應(yīng)包含所需要的應(yīng)用代碼或必須依賴的包含代碼的其它模塊。 參考 angular.modul
獲取更多信息。
在下面的例子中,如果 ngApp
指令沒被放在 html
元素上,文檔將不會被編譯, AppController
將不會被實例化,并且 {{ a+b }}
將不會被解析為 3
。
使用ngApp
是簡單、通用的啟動應(yīng)用的途徑。
<div ng-controller="ngAppDemoController">
I can add: {{a}} + {} = {{ a+b }}
</div>
script.jsangular.module('ngAppDemo', []).controller('ngAppDemoController', Function($scope) {
$scope.a = 1;
$scope.b = 2;});
ngStrictDi
,你會看到這樣的效果:<div ng-app="ngAppStrictDemo" ng-strict-di>
<div ng-controller="GoodController1">
I can add: {{a}} + {} = {{ a+b }}
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
</p>
</div>
<div ng-controller="GoodController2">
Name: <input ng-model="name"><br />
Hello, {{name}}!
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
</p>
</div>
<div ng-controller="BadController">
I can add: {{a}} + {} = {{ a+b }}
<p>The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
</p>
</div>
</div>
script.js
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', Function($scope) {
$scope.a = 1;
$scope.b = 2;})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', Function($scope) {
$scope.a = 1;
$scope.b = 2;}])
.controller('GoodController2', GoodController2);
Function GoodController2($scope) {
$scope.name= "World";}
GoodController2.$inject = ['$scope'];
style.cssdiv[ng-controller] {
margin-bottom: 1em;-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;}
<ANY
ng-app=""
[ng-strict-di=""]>
...
</ANY>
參數(shù) | 類型 | 詳述 |
---|---|---|
ngApp | angular.Module | 用于載入的可選的應(yīng)用 module 名稱。 |
ngStrictDi
(可選)
|
boolean | 如果在app元素上設(shè)置這個屬性, 注入器將使用 "strict-di" 模式創(chuàng)建。意思是,應(yīng)用將調(diào)用函數(shù)失敗在沒有使用明確的函數(shù)標(biāo)注時 (并且因此不適合于JavaScript壓縮), 在 依賴注入指南中,一些有用的調(diào)試信息將有助于追蹤這些錯誤的根源。 |