Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 216
rishal Avatar asked Jul 26 '14 16:07

rishal


People also ask

Where is the last element in NG-repeat?

$first and $last It's common when using ng-repeat to add specific behavior to the first or last element of the loop, e.g. special styling around the edges. Instead, ng-repeat already supplies you with two ready boolean properties. $first is true for the first element, and $last is true for the last element.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

How do I use track in NG-repeat?

Track by $index in AngularJSThe ngRepeat track by $index allows you to specify which items should be repeated using their index number. The ngRepeat is a directive that can be added to the HTML template of an Angular application. It is used for creating lists, and it can take an expression as an argument.

Does ng-repeat create a new scope?

However, some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element.


2 Answers

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

like image 177
Shomz Avatar answered Oct 16 '22 07:10

Shomz


You can use:

#social a:first-child{ /* your first css code */ } #social a:last-child{ /* your last css code */ } 
like image 28
Tony Chen Avatar answered Oct 16 '22 08:10

Tony Chen