Ng-app 指令的位置(html vs body)

我最近回顾了一个使用 angle 构建的 webapp 的代码,发现它是使用放置在 <body>标签上的 ng-app="myModule"指令编写的。当学习角度,我只看到它使用在 <html>标签,建议由有角度的医生 给你给你,并在他们的 教程

我自己对此进行了一些探索,发现了 SO 问题,特别是 这个和类似的 这个,它们讨论了如何为一个页面加载多个模块。但是,这种技术与我的情况不同,因为它涉及到将 ng-app 放在元素 内心的主体上,并使用手动引导来同时运行两个角度应用程序。

据我所知,<html><body>上具有 ng-app的应用程序在运行时没有区别。根据我的理解,ng-app指定了一个有角度应用程序的根,所以把它放在 <body>上会将 <head>从有角度应用程序的范围中切出来,但我想不出任何主要的方式来影响事情。因此,我的问题是: 在这些标签中的一个上而不是另一个上放置 ng-app,在技术上有什么区别?

38262 次浏览

There is no big difference where you put ng-app.

If you put it on <body> then you have a smaller scope for AngularJS which is slightly faster.

But I have used ng-app on the <html> for manipulating the <title>.

I was on a team working on a legacy app and found it best to use the ng-app tag in a div that is used as a wrapper to isolate new code from the legacy code.

We discovered this while working on the app that was heavily relying on jqGrid and Dojo.

When we added ng-app to the head tag it blew up the site, but when we used a wrapper we could use Angular with no problems.

AngularJS will bootstrap the first ng-app it finds! That's it. If you have more than one ng-app, it will only process the first one. If you want to bootstrap any other element use angular.bootstrap()

The value of the ng-app attribute is a module that have been created using:

angular.module("module_name", [])

A module defines how angular will bootstrapped because we do not have a main() method unlike other programming languages. If ng-app's value is empty, then it defaults to use 'ng', the default module.

It was said to be slightly faster because angular will process all of the elements inside the element where ng-app was. But I doubt slightly part because the difference will be hardly noticeable at all, unless you have a very very bulky DOM.

If you want examples here: http://noypi-linux.blogspot.com/2014/07/angularjs-tutorials-understanding.html