Chris W.
Chris W.

Reputation: 23280

Handling an expression outside of a repeat in ng-class

Can someone please let me borrow your eyes for a second because this has to be some dumb little nuance I'm missing here...?

So as example, within an ng-repeat I pull out a value and throw an inline expression at it like this (in this example, just changing some text color based on how many days old the value is):

EDIT* - scope.item doesn't mean anything in particular, I just edited the verbiage a little to get rid of any identifying names for the sake of an internet example.

ng-class="{
            'green-text':{{daysSinceToday(item.theItemDate) <= 20}},
            'orange-text':{{daysSinceToday(item.theItemDate) > 20 && daysSinceToday(item.theItemDate) < 30}},
            'red-text':{{daysSinceToday(item.theItemDate) >= 30}}
           }">

Which works splendidly, except then when I'm outside of the scope of the ng-repeat and try something similar but using just [0] on the item index like you see, then I can still get the value to display, but it doesn't seem to care about the ng-class expressions at all and instead just grabs the first class listed in the ng-class no matter what the value is.

So if I do something like this OUTSIDE of the ng-repeat;

ng-class="{
            'someclass':{{daysSinceToday(scope.item[0].theItemDate) <= 20}},
            'anotherclass':{{daysSinceToday(scope.item[0].theItemDate) > 20 && daysSinceToday(scope.item[0].theItemDate) < 30}},
            'yetanotherclass':{{daysSinceToday(scope.item[0].theItemDate) >= 30}}
           }">

It just doesn't seem to care, which is weird because if I just put it in there raw like;

{{daysSinceToday(scope.item[0].theItemDate)}}

Without the expression, it DOES give me the correct value but seems to ignore the ng-class. What am I missing here? I must be tired, and this monday should end on a high note lol. Thanks!

Upvotes: 0

Views: 88

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21475

Hah! File under I Blame Lack Of Caffeine, you want:

ng-class="{
            'someclass':daysSinceToday(scope.item[0].theItemDate) <= 20,
            'anotherclass':daysSinceToday(scope.item[0].theItemDate) > 20 && daysSinceToday(scope.item[0].theItemDate) < 30,
            'yetanotherclass':daysSinceToday(scope.item[0].theItemDate) >= 30
           }">

...no curlies necessary inside the ng-class.

(The rules for when you need {{}} and when you don't are arbitrary and confusing easy to overlook, as demonstrated quite clearly here)

Upvotes: 2

Mindastic
Mindastic

Reputation: 4121

You shoudn't be accessing it as scope.item[0]. I am not sure what is the variable you are iterating in ng-repeat but, assuming you are using something like items, you should access it just with items[0].whatever(...

Upvotes: 0

Related Questions