rishal
rishal

Reputation: 3548

Angular Js : How to find first and last element in ng-repeat and add special class to them?

I changed the following using angular js

<section id="social">
    <h2 class="line">Social Profiles</h2>
    <a href="#" class="first"><i class="icon-facebook"></i></a>
    <a href="#"><i class="icon-twitter"></i></a>
    <a href="#"><i class="icon-linkedin"></i></a>
    <a href="#"><i class="icon-google-plus"></i></a>
    <a href="#" class="last"><i class="icon-rss"></i></a>
    <div class="clear"></div>
</section>

To this

<section id="social">
    <h2 class="line">Social Profiles</h2>
    <a ng-repeat="sMedia in socialMedia" ng-if="$first" href="#" >
        <i class="{{sMedia.icon}}"></i>
    </a>
    <div class="clear"></div>
</section>

Everything seems fine except I could not find a way to add class="first" in the first element and class="last" in the last element of ng-repeat.

Upvotes: 22

Views: 28406

Answers (2)

Shomz
Shomz

Reputation: 37711

Just use $first and $last combined with ng-class:

<a ng-repeat="sMedia in socialMedia" ng-class="{'first': $first, 'last': $last}" href="#" >

See here how they work: https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 36

Tony Chen
Tony Chen

Reputation: 501

You can use:

#social a:first-child{ /* your first css code */ }
#social a:last-child{ /* your last css code */ }

Upvotes: 5

Related Questions