AngularJS ng-repeat Directive

Learn how ng-repeat clones an HTML element once for every item in an array or object to render lists and tables.

What ng-repeat Does

The ng-repeat directive clones an HTML element once for every item in an array (or the properties of an object), letting you turn a single template element into a full list, set of table rows, or grid of cards.

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="colors=['Red','Green','Blue']">
  <ul>
    <li ng-repeat="color in colors">{{ color }}</li>
  </ul>
</div>

</body>
</html>

Looping Over Arrays of Objects

ng-repeat is most useful with arrays of objects, where each cloned element can display several properties of the current item using ordinary expressions.

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="users=[
  {name:'Ada', age:36},
  {name:'Grace', age:85},
  {name:'Alan', age:41}
]">
  <table border="1">
    <tr ng-repeat="u in users">
      <td>{{ u.name }}</td>
      <td>{{ u.age }}</td>
    </tr>
  </table>
</div>

</body>
</html>

Special Variables Inside ng-repeat

Inside an ng-repeat loop, AngularJS exposes a handful of helper variables that describe the current position in the loop, which are handy for numbering rows or applying alternating styles.

  • $index — the zero-based position of the current item
  • $first — true if the current item is the first one
  • $last — true if the current item is the last one
  • $even / $odd — true depending on whether $index is even or odd

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="colors=['Red','Green','Blue']">
  <p ng-repeat="color in colors">
    {{ $index + 1 }}. {{ color }} <span ng-if="$last">(last one)</span>
  </p>
</div>

</body>
</html>
VariableMeaning
$indexCurrent index, starting at 0
$firsttrue on the first iteration
$lasttrue on the last iteration
$even / $oddtrue based on whether $index is even or odd
Note: By default ng-repeat expects unique items so it can track which DOM element belongs to which piece of data. When looping over a list that may contain duplicate primitive values, add track by $index to the expression, e.g. ng-repeat="n in numbers track by $index".