Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying multiple classes using ng-class

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:

  • the class names are generated dynamically based on object values
  • Foo classes are independent from Bar classes

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?

like image 855
jfu Avatar asked Dec 18 '25 14:12

jfu


2 Answers

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.

like image 103
jfu Avatar answered Dec 21 '25 08:12

jfu


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.

like image 44
Nikos Paraskevopoulos Avatar answered Dec 21 '25 08:12

Nikos Paraskevopoulos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!