Search code examples
angularjsangularjs-scopeangularjs-ng-repeatng-classng-switch

AngularJS - Apply class to <td> based on ng-switch statement


I have a simple ng-repeat on a <td>. Wihtin the ng-repeat is a ng-switch directive. I want to know how to apply a CSS class to a <td> when a a particular ng-switch condition is met.

<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>

However i am seeing the following error:

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

Solution

  • Your ng-init should be at the top so that it first gets initialized and then be used and do not forget that the switch will have its own scope so access the parent using $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