ng-switch内部ng-repeat不工作

时间:2013-05-21 15:42:36

标签: javascript html5 angularjs

我的数据基本上归结为:

function ExampleCtrl($scope) {
    $scope.myData= [
        {text: "blah", other: 3, V: 'caseOne'},
        {text: "blah", other: 3, V: 'caseTwo'},
        {text: "blah", other: 3, V: 'caseThree'}
    ];
}

这是这样使用的:

<div ng-controller="ExmapleCtrl">
    <table> 
       <tr> 
           <td>Text</td>
           <td>Other</td>
           <td>V</td>
       </tr>
       <tr ng-repeat="data in myData">
           <td><a href="#">{{data.text}}</a></td>
           <td>{{data.other}}</td>
           <td ng-switch on="data.V">
               <td ng-switch-when="caseOne"><img src="assets/img/pass.png"/></td>
               <td ng-switch-when="caseTwo"><img src="assets/img/pass.png"/></td>
               <td ng-switch-when="caseThree"><img src="assets/img/fail.png"/></td>
           </td>
    </table>
</div>

问题是我收到此错误:

Error: No controller: ngSwitch..

我清楚地将控制器设置为ExampleCtrl,我没有看到任何输入错误,所以我很遗憾。

2 个答案:

答案 0 :(得分:4)

我认为问题与产生无效标记的ng-switch有关。我不确定您是否可以将td嵌套在另一个td中。无论如何,如果你改成它,它将起作用:

 <td ng-switch on="data.V">
           <img src="assets/img/pass.png"  ng-switch-when="caseOne"/>
           <img src="assets/img/pass.png" ng-switch-when="caseTwo"/>
           <img ng-switch-when="caseThree" src="assets/img/fail.png"/>
       </td>

这是一个有效的演示:http://plnkr.co/edit/zUdkJYfnlJul6HsyCGfZ

我会继续并建议一些不使用可能更好的开关的解决方案。查看最后两个td

 <tr ng-repeat="data in myData">
           <td><a href="#">{{data.text}}</a></td>
           <td>{{data.other}}</td>

            <td>
               <img src='assets/img/{{data.V}}.png' />  <!-- assuming you have an image with name caseOne.png/caseTwo.png/etc -->
           </td>
           <td>
             <img src='{{passFail[data.V]}}' />   <!-- transform the case stuff to pass/fail based on some business rules, this is an object but could be a function-->
           </td>
      </tr>

$scope.passFail = {
  'caseOne' : 'assets/img/pass.png',
  'caseTwo' : 'assets/img/pass.png',
  'caseThree' : 'assets/img/fail.png'
};

答案 1 :(得分:1)

上述答案的附加内容   如果在td中只有纯文本,如switch case用户角色或其他东西,你可以在td中添加一个span标签来包含文本

<td ng-switch="role">
   <span ng-switch-when="1">Administrator</span>
   <span ng-switch-when="2">Moderator</span>
</td>