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

核能气质少年 提交于 2019-12-21 06:55:30

问题


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.


回答1:


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




回答2:


You can use:

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


来源:https://stackoverflow.com/questions/24973117/angular-js-how-to-find-first-and-last-element-in-ng-repeat-and-add-special-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!