问题
I want to display the elements of a list thanks to a ngSwitch but I can't figure out how to do with a ngRepeat. I've begun by doing it without a list, just to understand how ngSwitch works and to show you what I want to do, here's a jsFiddle that will help you understand: jdFiffle 1
Then, I try to use a list with ngRepeat but, whatever I try to do, it doesn't work. Here's a second jsFiddle with, this time, the use of a list: jsFiddle 2
It seems that ngClick and ngSwitch don't work when they're inside a ngRepeat... How can I do to make things work? Thanks in advance!
回答1:
Some problems:
When dealing with angular-directives, you usually don't need to use the
{{...}}syntax, just use the real values. So instead of:data-ng-click="sw='{{test.name}}'"use:
data-ng-click="sw = test.name"(see next point for why this won't be enough)
ng-repeatuses its own scope with transclusion, so the above will setswin the wrong scope, use:data-ng-click="$parent.sw = test.name"you can't build
ng-switch-when's withng-repeat, tryng-show/hideinstead try:<div ng-repeat="test in tests" ng-show="sw == test.name">
demo: http://jsbin.com/uxobot/1/
But all in all, I don't see the need for ng-switch/ng-repeat on the second div. The following has the same effect and is probably a lot more semantic:
<div ng-controller="MyCtrl">
<div class="click">
<div ng-repeat="test in tests" data-ng-click="$parent.active = test">
{{test.name}}
</div>
</div>
<div class="switch">
{{active.text}}
</div>
</div>
demo: http://jsbin.com/elufow/1/
来源:https://stackoverflow.com/questions/17694561/angularjs-ngswitch-and-ngclick-not-working-in-ngrepeat