John Henckel
John Henckel

Reputation: 11357

Angular apply style to the first visible item in ngRepeat

I have a list generated by ngRepeat, like so

<ul class="list-group">
    <li class="list-group-item" ng-repeat="data in tree | filter:key">
        {{data.name}}
    </li>
</ul>

and I want the first item in the list to have rounded corners. I have a style such as

.first-item {
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
}

How can I cause this style to be applied to the first visible item? Note that the key is connected to a search box, so the first item is dynamic.

Upvotes: 2

Views: 2577

Answers (5)

Sasi Kiran
Sasi Kiran

Reputation: 116

use $first, that represents the first iteration within a ng-repeat

<ul class="list-group">
    <li ng-class="{'first-item':$first}"
class="list-group-item" ng-repeat="data in tree | filter:key">
        {{data.name}}
    </li>
</ul>      

edit: since first-item has a dash, it must be in quotes

Upvotes: 6

Pratik Bhattacharya
Pratik Bhattacharya

Reputation: 3746

Use $first and ng-class. $first is a property which is exposed on the local scope, for each item in the repeated list. It's value is true if the item is the first one in the repeated list. The HTML should look something as below:

<ul class="list-group">
<li class="list-group-item" ng-repeat="data in tree | filter:key" ng-class="{'.first-item': $first}">
    <div>{{data.name}}</div>
</li>

Upvotes: 0

Digitrance
Digitrance

Reputation: 759

You can use the $index variable value to do such conditional formatting within ng-repeat. Here's an example:

<ul class="list-group">
    <li class="list-group-item" 
        ng-repeat="data in tree | filter:key" 
        ng-class="{'first-item': $index == 0}">
        {{data.name}}
    </li>
</ul>

Upvotes: 1

David
David

Reputation: 153

Pure Angular Way would be:

<ul class="list-group">
    <li class="list-group-item" ng-repeat="data in tree | filter:key track by $index" ng-class="{MyClassName: $index == 0}">
        {{data.name}}
    </li>
</ul>

or see answer of Sasi Kiran ;)

Upvotes: 2

FakeSkdr
FakeSkdr

Reputation: 106

You can use the css rule first-child:

.list-group li:first-child { 
     border-top-left-radius: 15px;
     border-top-right-radius: 15px;
}

http://www.w3schools.com/cssref/sel_firstchild.asp

Upvotes: 4

Related Questions