Angular Js:如何在ng-repeat中找到第一个和最后一个元素并为它们添加特殊类?

时间:2022-11-09 12:08:10

I changed the following using angular js

我使用角度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.

一切似乎都很好,除了我找不到在第一个元素中添加class =“first”和在ng-repeat的最后一个元素中添加class =“last”的方法。

2 个解决方案

#1


34  

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

只需使用$ first和$ last结合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

看看它们是如何工作的:https://docs.angularjs.org/api/ng/directive/ngRepeat

#2


5  

You can use:

您可以使用:

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

#1


34  

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

只需使用$ first和$ last结合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

看看它们是如何工作的:https://docs.angularjs.org/api/ng/directive/ngRepeat

#2


5  

You can use:

您可以使用:

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