问题描述
JS
$scope.mode = "test"$scope.array = ['test1', 'test2', 'test3']
HTML
<div ng-repeat="数组中的项目" ng-switch-when="test">测试项目}}
JS
$scope.mode = "test"$scope.array = ['test1', 'test2', 'test3']
HTML
<div ng-repeat="数组中的项目" ng-switch-when="test">测试项目}}
当我执行上述操作时,我得到的输出是
测试测试测试
它似乎无法访问项目.如果我删除 ng-switch-when 那么它就可以正常工作.
这是因为 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 版本.
现在从 1.3.x 版本的 angular 起,ng-switch 的优先级已经修改为 1200 和 ng-repeat 保持在 1000,因此 ng-repeated 范围将占上风,因为它现在的优先级较低,并且在这种情况下可以工作.
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
It can't seem to access item. If I remove the ng-switch-when then it works fine.
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.
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.
这篇关于ng-repeat 和 ng-switch 在同一个元素上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!