Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to add multiple ng-class directives?

Here are 2 different ways to use the ng-class directive. I need them both, on the same element, but that doesn't work.

Using an object in ng-class

http://plnkr.co/edit/uZNK7I?p=preview

<div ng-repeat="item in [1, 2, 3, 4, 5]" 
     ng-class="{ first: $first, last: $last }">{{item}}</div>

correctly results in

<div class="first">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div class="last">5</div>

Using an expression in ng-class

http://plnkr.co/edit/tp6lgR?p=preview

<div ng-repeat="item in [1, 2, 3, 4, 5]" 
     ng-class=" 'count-' + ($index + 1) ">{{item}}</div>

correctly results in

<div class="count-1">1</div>
<div class="count-2">2</div>
<div class="count-3">3</div>
<div class="count-4">4</div>
<div class="count-5">5</div>

Now, how about use them together?

I need dynamic class names (like 'count-' + n), but also need the object syntax for multiple classes.

I can't just use 2 ng-class attributes (http://plnkr.co/edit/OLaYke?p=preview), only the first one works.

Any suggestions?

like image 682
Michael Lewis Avatar asked Mar 28 '14 19:03

Michael Lewis


People also ask

Can you have two ngClass?

Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.

Can we use NGIF and ngClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What is ngClass in AngularJS?

The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. The value for the ng-class has either string, an object, or an array. It must contain more than one class name, which is separated by space, in the case of a string.

How do you add ngClass based on condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.


Video Answer


2 Answers

You shouldn't be using ng-class for the second one, use

<div class="count-{{$index + 1}}" ng-class="{ first: $first, last: $last }">
like image 182
tymeJV Avatar answered Oct 29 '22 20:10

tymeJV


You should provide ngClass with an array that contains both expression and object:

<div ng-class="['count-' + ($index + 1), { first: $first, last: $last }]">

Note: The solution suggested in accepted answer (simultaneous usage of ngClass directive and interpolation in class attribute) is a bad practice. See more details here and here.

like image 25
Maxim Kulikov Avatar answered Oct 29 '22 19:10

Maxim Kulikov