1

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
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Oam Psy
  • 8,555
  • 32
  • 93
  • 157
  • 2
    You are supposed to wrap `darkGrey: darkenCell == 1` in curly braces `{darkGrey: darkenCell == 1}` for starters. – Sergiu Paraschiv Aug 20 '14 at 10:35
  • @SergiuParaschiv - that gets rid of the error but cant see the CSS being applied. Do i need to initialise darkenCell = 0 in my controller? – Oam Psy Aug 20 '14 at 10:49

1 Answers1

3

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

V31
  • 7,626
  • 3
  • 26
  • 44
  • But i only want the cell to have darkGrey CSS class if the ng-switch-default case is triggered, hence the 'Dark' text. – Oam Psy Aug 20 '14 at 11:04
  • @OamPsy: updated the answer, if you want to show a class on default you need to use ng-class on that element – V31 Aug 20 '14 at 11:08
  • Im not sure if i am explaining incorrectly. I am displaying a lsit of 's... Which either say, U,D,2,3,4 or Dark... For the 's that say Dark, i want that to have the darkGrey CSS class. – Oam Psy Aug 20 '14 at 11:10
  • Although that logic makes sense, the CSS class is failing to be applied. – Oam Psy Aug 20 '14 at 11:21
  • Thank you wokring as expected. – Oam Psy Aug 20 '14 at 11:39