Skip to content Skip to sidebar Skip to footer

AngularJS - NgSwitch And NgClick Not Working In NgRepeat

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 ngSwit

Solution 1:

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/


Post a Comment for "AngularJS - NgSwitch And NgClick Not Working In NgRepeat"