AngularJS - ngSwitch and ngClick do not work in ngRepeat

I want to display list items thanks ngSwitch, but I cannot figure out how to do this with ngRepeat. I started doing this without a list, just to understand how it works ngSwitchand show you what I want to do, here is jsFiddle to help you understand: jdFiffle 1

Then I try to use a list with ngRepeat, but, whatever I try to do, it does not work. Here's the second jsFiddle, this time using a list: jsFiddle 2

It seems that ngClickthey ngSwitchdon’t work when they are inside ngRepeat... How can I make it work? Thanks in advance!

+3
source share
1 answer

Some problems:

  • When working with angular-directives, you usually do not need to use syntax {{...}}, just use real values. Therefore, instead of:

    data-ng-click="sw='{{test.name}}'"
    

    using:

    data-ng-click="sw = test.name"
    

    (see next paragraph why this is not enough)

  • ng-repeatuses its scope with the transition, so the above value will be swin the wrong scope, use:

    data-ng-click="$parent.sw = test.name"
    
  • you cannot build ng-switch-whenwith ng-repeat, try to try ng-show/hideinstead:

    <div ng-repeat="test in tests" ng-show="sw == test.name">
    

demo: http://jsbin.com/uxobot/1/


But overall, I don't see the need ng-switch/ng-repeatfor a second div. The following has the same effect and 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/

+11

All Articles