Mike Lewis Mike Lewis - 1 year ago 113
AngularJS Question

AngularJS - How to add multiple ng-class directives?

Here are 2 different ways to use the

directive. I need them both, on the same element, but that doesn't work.

Using an object in ng-class


<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 class="last">5</div>

Using an expression in ng-class


<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
attributes (http://plnkr.co/edit/OLaYke?p=preview), only the first one works.

Any suggestions?

Answer Source

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

<div class="count-{{$index + 1}}" ng-class="{ first: $first, last: $last }">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download