本文介绍了ng-repeat和ng-switch在相同元素上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JS

$scope.mode = "test"
$scope.array = ['test1', 'test2', 'test3']

HTML

<div ng-switch on="mode">
    <div ng-repeat="item in array" ng-switch-when="test">
        Test {{item}}
    </div>
</div>

在上述操作中,我得到的输出是

When I do this the above, the output I get is

Test Test Test

似乎无法访问该项目.如果我将ng-switch-when删除,则可以正常工作.

It can't seem to access item. If I remove the ng-switch-when then it works fine.

推荐答案

这是因为 ng-switch 创建了一个子作用域,并且同样适用于ng-repeat.ng-repeat优先运行 1000 ng-switch 800 .因此,由 ng-repeat 在每个重复的div元素上创建的子范围将由 ng-switch 覆盖,因此分配了 ng-repeat 元素上的子作用域最终消失了.一种可能的方法是将ng-switch包装在ng-repeat之外,因为您始终不想为每个重复的元素评估ng-switch表达式.这是1.2版.

It is because ng-switch creates a child scope and same applies for ng-repeat. ng-repeat runs at priority 1000 and ng-switch at 800. So the child scope created by ng-repeat on each of the repeated div elements gets overwritten by ng-switch, so the ng-repeat assigned child scope on the element is gone ultimately. A possibly way could be to wrap your ng-switch outside ng-repeat since you anyways do not want to evaluate the ng-switch expression for every repeated element. This is with the 1.2 version.

现在从Angular的1.3.x版本开始,ng-switch的优先级已修改为 1200 ,而ng-repeat仍为 1000 ,因此ng重复范围将占上风,因为它现在的优先级较低,并且在这种情况下可以使用.

Now from 1.3.x version of angular the priority of ng-switch has been revise to 1200 and ng-repeat remains at 1000, so ng-repeated scope will prevail, since it is of lower priority now and it will work in that case.

Plnkr

Plnkr

这篇关于ng-repeat和ng-switch在相同元素上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:07