简体   繁体   English

为什么ng-controller和ng-repeat在Angular JS中的同一个标签内不能同时工作?

[英]Why ng-controller and ng-repeat doesn't work together inside same tag in Angular JS?

The below code is not working since i used both ng-controller and ng-repeat inside same tag. 由于我在同一标签内使用了ng-controller和ng-repeat,因此下面的代码无效。 But if i use ng-repeat inside child div, its working. 但是,如果我在子div中使用ng-repeat,它的工作。 Why? 为什么?

**Not Working**
<div ng-controller="myController" ng-repeat= "object in objectArray">
{{object.State}}
{{oject.Capital}}
</div>


**Working**
<div ng-controller="myController" >
<div ng-repeat= "object in objectArray">
{{object.State}}
{{oject.Capital}}
</div>
</div>

Here: 这里:

The Logical Reason: 逻辑原因:

<div ng-controller="myController" ng-repeat= "object in objectArray">
{{object.State}}
{{oject.Capital}}
</div>

As you know, ng-repeat is multiplicating the containing tag, so here, there will be a lot of controllers on the same page like this: 如您所知,ng-repeat正在使包含标记倍增,所以在这里,同一页面上会有很多控制器,如下所示:

<div ng-controller="myController" ng-repeat= "object in objectArray">
    lorem
    ipsum
</div>
<div ng-controller="myController" ng-repeat= "object in objectArray">
    lorem
    ipsum
</div>
<div ng-controller="myController" ng-repeat= "object in objectArray">
    lorem
    ipsum
</div>

So this is why you cannot use them in the same tag, you have to separate them like you did in your second example. 所以这就是为什么你不能在同一个标​​签中使用它们,你必须像在第二个例子中那样分开它们。

The Main Reason: 主要原因:

Also, the main logic is, you can manage the components inside the controller's ones, not others; 此外,主要逻辑是,您可以管理控制器内部的组件,而不是其他组件; so your angular components that you want to manage like ng-repeat, ng-if or ng-model they all should be inside a unique controller tag, not at the same level. 因此,您想要管理的角度组件,如ng-repeat,ng-if或ng-model,它们都应位于唯一的控制器标签内,而不是在同一级别。

To provide this, AngularJS library gives priority to the components like controllers have the highest ones than the other components like ng-repeat has lower, so the controller tag will be compiled first and then the others. 为了提供这一点,AngularJS库优先考虑控制器的组件比其他组件(例如ng-repeat低)的组件最高,因此控制器标签将首先编译,然后编译其他组件。 If the compiler sees some errors like syntactical errors, it will inform the coder to not to do those. 如果编译器看到一些错误,如语法错误,它将告知编码器不要执行这些操作。

You can read more about the priorities in AngularJS here . 您可以在此处阅读有关AngularJS优先级的更多信息。

According to the docs, ng-repeat as a directive has a priority of 1000, and ng-controller a priority of 500, meaning that ng-repeat will get compiled first, and the objectArray array you are referring to is bound to the scope of myController which has not been initialized yet, so ng-repeat will in that case fail. 根据文档, ng-repeat作为指令的优先级为1000, ng-controller的优先级为500,这意味着ng-repeat将首先被编译,并且您引用的objectArray数组绑定到尚未初始化的myController ,因此在这种情况下ng-repeat会失败。

Nice post about directive priority: 1 关于指令优先权的好帖子: 1

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

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