简体   繁体   English

HTML元素上的ng-app是否像开/关开关一样起作用?

[英]Does ng-app on HTML element act like an on/off switch?

I'm using Angular 1.6.1. 我正在使用Angular 1.6.1。 The goal is to click on a list item, and it shows the tab number. 目的是单击列表项,并显示选项卡编号。 This bit of code doesn't work on its own: 这段代码不能单独工作:

<ul>
    <li ng-click="tab = 1" >
        Thing 1
    </li>
    <li ng-click="tab = 2" >
        Thing 2
    </li>
</ul>
<p>{{tab}}</p>

However, once we add this, it works: 但是,一旦我们添加了它,它就会起作用:

<html ng-app="">
</html>

And it even works when the ul is outside the ng-app scope. ulng-app范围之外时,它甚至可以工作。 So: 所以:

<ul>
    <li ng-click="tab = 1" >
        Thing 1
    </li>
    <li ng-click="tab = 2" >
        Thing 2
    </li>
</ul>
<p>{{tab}}</p>

<html ng-app="">
</html>

Does not work when element is a div : 当element是div时不起作用:

<div ng-app="">
</div>

Am I just mixing up an understanding of some low-level HTML functionality, or how is this working? 我是否只是对一些底层HTML功能的理解混淆了,或者这是如何工作的?

ng-app bootstraps Angular on your code. ng-app bootstraps在代码上使用Angular。 You can put it on the body tag if you prefer, but your Angular code must be in that block. 如果愿意,可以将其放在body标签上,但是Angular代码必须在该代码块中。

I would not say that "ng-app acts like an on/off switch" , and I do not recommend using it like this . 我不会说“ ng-app就像一个开/关开关”我不建议这样使用它

If you want to "activate/desactivate" some parts of your code, you should use ng-if (or other, it depends of your needs) . 如果要“激活/停用”代码的某些部分,则应使用ng-if (或其他,取决于您的需要)


From the examples you provided: 从您提供的示例中:

Example 1 例子1

It does not as Angular is not bootstraped in your application (as explained before) 不会,因为Angular没有在您的应用程序中引导(如前所述)

Example 2 例子2

It works, as it is the good way to write your code 它有效,因为它是编写代码的好方法

Example 3 例子3

It is probably the most strange: As your document is not well-written and not HTML valid , your code is rewritted by your browser. 这可能是最奇怪的:由于您的文档编写不正确HTML无效 ,因此您的代码已由浏览器重新编写。 So: 所以:

<ul>
  ...
</ul>
<p>{{tab}}</p>

<html ng-app="">
</html>

Becomes 成为

<html ng-app="">
  <ul>
    ...
  </ul>
  <p>{{tab}}</p>
</html>

Example #4 例子#4

It does not work, as your Angular code is not inside this div (and it is not rewritted by your browser like Example #3). 这是行不通的,因为你的角码是不是这个div (并且它不是由您的浏览器就像例3 rewritted)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM