ng-switch 和 ng-repeat 对同一元素进行干扰 [英] ng-switch and ng-repeat on the same element interfearing
问题描述
我在 Angular 中遇到了我没想到的行为,这篇文章的目的是找出这是一个错误还是有意为之,并可能解释为什么要这样做.
I encountered behaviour in Angular I did not expect and the purpose of this post is to find out whether this is a bug or intended and possibly an explanation why it is intended.
首先看到这个Plunkr:http://plnkr.co/edit/CB7k9r?p=preview .在示例中,我创建了一个名为 array 的数组,其中包含三个对象条目.此外,我根据输入字段的内容(称为切换)创建了一个 ng-switch.当toggle的值为1时,它应该打印数组中以1"为前缀的所有对象名称,否则以other"为前缀.
First see this Plunkr: http://plnkr.co/edit/CB7k9r?p=preview . In the example I created an array called array with three object entries. Further I created a ng-switch based on the content of an input field (called toggle). When the value of toggle is 1 it should print all names of the objects in the array prefixed with "1" and otherwise prefixed with "other".
这不能正常工作并显示错误:
This does not work as intended an it shows an error:
Error: Argument '?' is required at assertArg
然而,重写了相同的示例(http://plnkr.co/edit/68Mfux?p=preview ) 在列表周围有一个额外的 div,ng-switch 移动到这个 div,ng-switch-when 从 li 移动到 ul(将 ng-repeat 和 ng-switch-when 分开)确实按预期工作.
However the same example rewritten (http://plnkr.co/edit/68Mfux?p=preview ) with an extra div around the list, the ng-switch moved to this div and the ng-switch-when moved from the li to the ul (separating the ng-repeat and the ng-switch-when) does work as intended.
谁能解释一下这是为什么?
Could someone explain why this is?
推荐答案
这是有意的",因为它是 angular 如何处理 ng-repeat 的产物.本质上,标记的多个副本被克隆(ng-repeat 中的标记用作模板)并为您正在迭代的每个元素单独编译.因此,angular 基本上是编译 3 和 3
It is "intentional", as it is a product of how angular handles ng-repeat. Essentially, multiple copies of the markup are cloned (the markup inside ng-repeat is used as a template) and are compiled individually for each element you are iterating. As such, angular is basically compiling 3 <li ng-switch-when='1' ....>
and 3 <li ng-switch-default ....>
, but doing so out of context - there is no ng-switch-on element to compare to.
您可以通过检查生成的标记来看到这种情况:
You can see this happening by inspecting the resulting markup:
<ul ng-switch="" on="toggle">
<!-- ngRepeat: entry in array -->
<!-- ngSwitchWhen: 1 -->
<!-- ngSwitchWhen: 1 -->
<!-- ngSwitchWhen: 1 -->
<!-- ngRepeat: entry in array -->
<!-- ngSwitchDefault: -->
<!-- ngSwitchDefault: -->
<!-- ngSwitchDefault: -->
</ul>
这两个指令 - ng-repeat 和 ng-switch - 都应该小心处理,因为它们(不像,例如,ng-show 或 ng-hide)严重影响结构.第二个(工作)Plunker 是要走的路 - 仅在(结构上,内部)ng-switch 逻辑之后使用指令.
Both directives - ng-repeat and ng-switch - should be handled with care, as they (unlike, for instance, ng-show or ng-hide) heavily influence structure. The second (working) Plunker is the way to go - only work with directives AFTER (structure-wise, INSIDE) the ng-switch logic.
这篇关于ng-switch 和 ng-repeat 对同一元素进行干扰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!