3

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!

Sylla
  • 113
  • 1
  • 10

1 Answers1

11

Some problems:

  1. 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)

  2. ng-repeat uses its own scope with transclusion, so the above will set sw in the wrong scope, use:

    data-ng-click="$parent.sw = test.name"
    
  3. you can't build ng-switch-when's with ng-repeat, try ng-show/hide instead 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/

roufamatic
  • 18,187
  • 7
  • 57
  • 86
Yoshi
  • 54,081
  • 14
  • 89
  • 103