NG-开关和NG-重复同一元素interfearing上 [英] ng-switch and ng-repeat on the same element interfearing
问题描述
在我遇到的角行为没想到和这个职位的目的是找出这究竟是为什么它的目的是错误或意图和可能的解释。
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=$p$ PVIEW 。在这个例子中,我创建三个参赛对象的数组称为数组。另外我创建了一个基于输入字段(称为切换)的内容的NG-开关。当切换的值为1就应该打印对象的所有名称中以1pfixed数组$ P $否则$ P $与pfixed其他。
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=$p $ PVIEW )与周围的名单一个额外的div时,NG-开关移到这个DIV和NG-开关时,从里搬到了UL(分离NG重复和NG-开关时)不按预期工作。
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?
推荐答案
这是故意的,因为它是如何角手柄NG-重复的产物。本质上,标记的多拷贝克隆(纳克重复内的标记被用作模板)并且分别为要遍历每个元素编译。因此,角基本上是编译3 <李NG-开关时='1'...>
3 <李NG-开关默认....方式>
,但这样做断章取义 - 没有NG-接通元素来比较
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-开关 - 应小心处理,因为它们(不像,例如,NG-显示或NG-隐藏)严重影响结构。第二个(工作)Plunker是要走的路 - 只有指令后(结构的角度来看,内部)的NG-切换逻辑工作
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-开关和NG-重复同一元素interfearing上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!