tome
tome

Reputation: 1196

ngClass - creating a class name containing angular expression

I would like to create class names based on an the evaluation of an angular expression, but it seems that angular is removing these expressions from the eventually compiled classes. When iterating over cells, assume the following code:

<td ng-class="{'label{{cell.count}}': !!cell.count}"></td>

My goal is that when cell.count = 1 the resulting class will be "label1", when cell.count = 2, "label2", etc. In practice, what happens is that angular discards the expression in the eventual class - As long as !!cell.count, I get the class "label" regardless of the count. How can I achieve this?

Upvotes: 1

Views: 1796

Answers (3)

Martin
Martin

Reputation: 1

I had the same issue. I managed to solve it like this:

<td ng-class="{['label' + cell.count]: !!cell.count}"></td>

Upvotes: 0

nephiw
nephiw

Reputation: 2046

Did you ever try: <td ng-class="'label' + cell.count"></td> - simply not using the curly braces works for me in my project (angular 1.5).

Upvotes: 0

Duncan
Duncan

Reputation: 95652

Try this:

<td ng-class="{'label'+cell.count: !!cell.count}"></td>

If it gets too complicated you can also move the entire object out into a function in the scope.

<td ng-class="getCellClass()"></td>

and then:

$scope.getCellClass = function() { ... }

Your problem is that the {{...}} substitution isn't appropriate here. You have to use an angular expression to create the object, or if you call a method on the scope you can do any javascript you need to create it.

Upvotes: 2

Related Questions