JamesDeveloper
JamesDeveloper

Reputation: 113

How do i use a ng-repeat with different classes with each index

I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

<ul class="timeline">
    <li ng-repeat-start="t in vm.patientTimeLine">
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
            <div class="card-block">
                 <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
            </div>
     </li>

     <li class="timeline-inverted" ng-repeat-end>
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
           <div class="card-block">
               <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
           </div>
     </li>
</ul>

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

Upvotes: 0

Views: 348

Answers (3)

Matthew Zackschewski
Matthew Zackschewski

Reputation: 486

You can use the $index and potentially do an

ng-class="{'timeline': $even, 'timeline-inverted': $odd}"

The better option (in my opinion) is to use css classes "nth-child" to alter classes using css. Check out W3Schools nth-child to find it. I'm new to stack overflow so I'm not sure how to use JSFiddle but you could potentially use:

.timeline-inverted :nth-child(even) // Even Elements

.timeline-inverted :nth-child(odd) // Odd Elements

I'm unsure where you want to apply the class but if you wanted to change the class of a div element with your ngRepeat, you can do the following:

.timeline-inverted div:nth-child(even)
.timeline-inverted div:nth-child(odd)

Hopefully this answers your question.

Upvotes: 1

Anthony
Anthony

Reputation: 1827

vicbyte's answer is correct, but I wanted to add a little more context.

ng-class can be used to conditionally apply classes with the items in ng-repeat.

<li ng-repeat="i in items" ng-class="{ 'inverted': $even }"></li>

Upvotes: 1

vicbyte
vicbyte

Reputation: 3790

If you want to lets say, make timeline-inverted every other row, you can always use the varaibles ngRepeat provides. For example:

$even   boolean     true if the iterator position $index is even (otherwise false).

List of variables can be found here: https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 3

Related Questions