Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-repeat add some text with first element

I am using ng-repeat and would like to ask if we can add some extra text with first item?

 var items = [1,2,3,4,5,6,7,8,9]

 <div ng-repeat="item in items">
     {{item}}
 </div>

What i want is, it return me result like:

1 Hello
2
3
4
5
6
7
8
9

Thanks.

like image 600
Aqdas Avatar asked Jan 18 '26 03:01

Aqdas


2 Answers

Take advantage of the angular $index variable, that gives you the index of the item in the collection:

<div ng-repeat="item in items">
     {{item}} <span ng-if="$index === 0">Hello</span>
</div>

or

<div ng-repeat="item in items">
     {{item}} <span ng-if="$first">Hello</span>
</div>

See documentation

You have the following special values:

  • $first
  • $middle
  • $last
  • $even
  • $odd
like image 140
Michael P. Bazos Avatar answered Jan 19 '26 15:01

Michael P. Bazos


Can use a variety of special properties added to the child scope in ng-repeat and for this it includes $first along with $index, $last, $middle, $even, $odd

<div ng-repeat="item in items">
     {{item}} {{ $first ? 'I am first item' :''}}
 </div>
like image 22
charlietfl Avatar answered Jan 19 '26 17:01

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!