Assume that I have two objects in my model: foo that can take two values Foo1 and Foo2 and object bar with two possible values Bar1 and Bar2.
Now, I would like to apply to my div classes based on values of these objects.
Basically, I would like to apply MyclassFoo1 when foo=Foo1, MyclassFoo2 when foo=Foo2 and similarly for bar.
For instance, if foo=Foo1 and bar=Bar2 I would like to end up with
<div class="MyClassFoo1 MyClassBar2"></div>
The two problems that I am having here are:
I've tried to use the syntax
<div ng-class="{class1: expr1, class2: expr2}"></div>
but it doesn't work, as the dictionary keys cannot be composed as 'MyClass' + foo
The other syntax
ng-class="{expr_val1: class1, expr_val2: class2}[expr]"
does not look promissing either: I would have to put all the foo-bar combinations as expression values.
Is there any other way to achieve my goal?
I've managed to solve the problem entirely in template, using the list notation in the following way:
ng-class="[foo ? 'MyClass' + foo : '', bar ? 'MyClass' + bar : '']"
You can put arbitrary angular expressions into the list.
Have you tried the following?
<div class="MyClass{{model.foo}} MyClass{{model.bar}}">
Even if model.foo or .bar becomes null this will add a non-existing class, which should not matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With