AngularJS - ngSwitch and ngClick not working in ngRepeat

耗尽温柔 提交于 2019-12-10 21:24:50

问题


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:

  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/



来源:https://stackoverflow.com/questions/17694561/angularjs-ngswitch-and-ngclick-not-working-in-ngrepeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!