AngularJS ng-app的自动加载与属性值

前端之家收集整理的这篇文章主要介绍了AngularJS ng-app的自动加载与属性值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


ng-app 指令用于告诉 AngularJS 应用当前这个元素是根元素,所有 AngularJS 应用都必须要要一个根元素。


使用ng-app来标记一个DOM结点,在网页加载完毕时会自动引导自动初始化)应用程序。

ng-app可以带属性值,可以指定加载应用模块的名称,ng-app="模块名称"。


但是HTML文档中只允许有一个 ng-app 指令,如果有多个 ng-app 指令,则只有第一个会被使用。

所以想要实现自动加载,那么就不能让ng-app带有属性值,即不能指定载入应用模块名称


正确写法

  1. <bodyng-app>
  2. <div><p>{{5+5}}</p></div>
  3. <div><p>{{10+10}}</p></div>
  4. </body>


只加载第一个块

  1. <body>
  2. <divng-app><p>{{5+5}}</p></div>
  3. <divng-app><p>{{10+10}}</p></div>
  4. </body>


以下为ng-app添加属性值的写法都是错误的,会报错

  1. <bodyng-app=“myApp”>
  2. <div><p>{{5+5}}</p></div>
  3. <div><p>{{10+10}}</p></div>
  4. </body>


  1. <body>
  2. <divng-app=“app1”><p>{{5+5}}</p></div>
  3. <divng-app=“app2”><p>{{10+10}}</p></div>
  4. </body>



属性值时候需要手动加载对应ng-app

  1. <body>
  2. <divid="app1"ng-app="app1">{{5+5}}</div>
  3. <divid="app2"ng-app="app2">{{10+10}}</div>
  4. <scripttype="text/javascript">
  5. varapp1=angular.module("app1",[]);
  6. varapp2=angular.module("app2",[]);
  7. angular.bootstrap(document.getElementById("app2"),['app2']);
  8. </script>
  9. </body>

app1会自动加载

app2需要手动加载


angular.bootstrap() ,手动启动 AngularJS

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


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

Arguments

Param Type Details
element DOMElement

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 模块名数组

猜你在找的Angularjs相关文章