ng-repeat

Description

ng-repeat iterates over a collection and creates new template for each item in the collection. Each item in the collection is given its own template and scope.

ng-repeat has special properties:

  • $index - iterator offset of the repeated element (0 ... length - 1)
  • $first - true if the repeated element is first in the iterator
  • $middle - true if the repeated element is between the first and last in the iterator
  • $last - true if the repeated element is last in the iterator
  • $even - true if the iterator position $index is even (otherwise false)
  • $odd - true if the iterator position $index is odd (otherwise false)

Example

The following code shows how to ng-repeat. It uses $odd and $even.


<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
  <style>
    .odd {<!--from ww w . j ava2s .c  o  m-->
      background-color: blue;
    }
    .even {
      background-color: red;
    }
  </style>
</head>
<body>

  <ul ng-controller="MyController">
    <li ng-repeat="person in people" ng-class="{even: !$even, odd: !$odd}">
      {{person.name}} lives in {{person.city}}
    </li>
  </ul>

  <script>
    angular.module('myApp', [])
    .controller('MyController', function($scope) {
      $scope.people = [
        {name: "A", city: "San Francisco"},
        {name: "B", city: "New York"},
        {name: "C", city: "Vancouver"},
        {name: "D", city: "San Diego"},
        {name: "E", city: "Paris"},
        {name: "F", city: "London"},
        {name: "G", city: "Beijing"},
        {name: "H", city: "HongKong"},
        {name: "I", city: "Toyou"},
        {name: "J", city: "Seattle"}
      ];
    });
  </script>

</body>
</html>

Click to view the demo





















Home »
  AngularJS »
    AngularJS Tutorial »




Introduction
Buildin Filters
Buildin Directives