Is it possible to have multiple separate ternary expressions in ng-class for an element?
For anyone looking for the answer: Yes this is indeed possible, also as mentioned the readability is questionable.
<div ng-class="(conversation.read ? 'read' : 'unread') + ' ' + (conversation.incoming ? 'in' : 'out')"></div>
From the ngClass documentation:
The directive operates in three different ways, depending on which of >three types the expression evaluates to:
If the expression evaluates to a string, the string should be one or >more space-delimited class names.
If the expression evaluates to an array, each element of the array >should >be a string that is one or more space-delimited class names.
If the expression evaluates to an object, then for each key-value pair of >the object with a truthy value the corresponding key is used as a class >name.
Option 1 applies here.
From my understanding using this method will result in 2 watches while using object notation will result in 4, but I might be wrong on this one.
I think you'd rather use a filter. You could write a rateToClass
filter that would hold the logic and transform your rate in the class name that you want.
You could also put a rateToClass(rate) function in your scope, but it's ugly.
If you insist on having your logic in the view,
ng-class
support multiple classes by using an object (see official doc first example, line 7):
<p ng-class="{strike: strike, bold: bold, red: red}">Map Syntax Example</p>
You can have more complexe expression like ng-class='{btn-success: rate > 0}
'.
It is possible to add multiple ternary expressions on a single ng-class directive by putting each of the expressions into an array, as items of this array.
Example :
<div ng-class="[
expression1 ? 'class1' : 'class2',
expression2 ? 'class3' : 'class4'
]">