AngularJS - 根据ng-switch语句应用类

时间:2014-08-20 10:33:20

标签: angularjs angularjs-scope angularjs-ng-repeat ng-class ng-switch

我在<td>上有一个简单的ng-repeat。使用ng-repeat是一个ng-switch指令。我想知道如何在满足特定的ng-switch条件时将CSS类应用于<td>

<td ng-repeat="deposit in MyData.MyDeposits.slice(0, 12)" ng-switch="deposit" ng-class="darkGrey: darkenCell == 1">
    <span ng-switch-when="0">U</span>
    <span ng-switch-when="1">D</span>
    <span ng-switch-when="2">2</span>
    <span ng-switch-when="3">3</span>
    <span ng-switch-when="4">3</span>
    <span ng-switch-default ng-init="darkenCell = 1" >Dark</span>
</td>

但是我看到以下错误:

Error: [$parse:syntax] http://errors.angularjs.org/1.2.8/$parse/syntax?p0=%3A&p1=is%20an%20unexpected%20token&p2=6&p3=darkGrey%3A%20darkenCell%20%3D%3D%201&p4=%3A%20darkenCell%20%3D%3D%201

1 个答案:

答案 0 :(得分:3)

你的ng-init应该在顶部,这样它首先被初始化然后被使用,不要忘记交换机将有自己的范围,所以使用$ parent

访问父节点
<td ng-init="darkenCell = 0" ng-repeat="deposit in MyData.MyDeposits.slice(0, 12)" ng-switch="deposit" ng-class="{darkGrey: darkenCell == 1}">
    <span ng-switch-when="0">U</span>
    <span ng-switch-when="1">D</span>
    <span ng-switch-when="2">2</span>
    <span ng-switch-when="3">3</span>
    <span ng-switch-when="4">3</span>
    <span ng-switch-default ng-show="$parent.darkenCell = 1">Dark</span>
</td>

Plunkr Example