Episode 7 of 25

The ng-repeat Directive

Learn how to loop through arrays and objects with ng-repeat.

The ng-repeat directive is like a for loop — it repeats an HTML element for each item in a collection.

Basic ng-repeat

<div ng-app="" ng-init="fruits=['Apple','Banana','Cherry','Date']">
    <ul>
        <li ng-repeat="fruit in fruits">{{ fruit }}</li>
    </ul>
</div>

With a Controller

app.controller('TodoCtrl', function($scope) {
    $scope.todos = [
        { task: 'Learn AngularJS', done: true },
        { task: 'Build project', done: false },
        { task: 'Deploy app', done: false }
    ];
});
<div ng-controller="TodoCtrl">
    <ul>
        <li ng-repeat="todo in todos">
            {{ todo.task }} - {{ todo.done ? 'Done' : 'Pending' }}
        </li>
    </ul>
</div>

Special Variables

AngularJS provides special variables inside ng-repeat:

<li ng-repeat="item in items">
    {{ $index }}     <!-- Current index (0-based) -->
    {{ $first }}     <!-- true if first item -->
    {{ $last }}      <!-- true if last item -->
    {{ $even }}      <!-- true if even index -->
    {{ $odd }}       <!-- true if odd index -->
</li>

Looping Through Objects

<div ng-init="user={name:'Alice', age:25, city:'London'}">
    <p ng-repeat="(key, value) in user">
        {{ key }}: {{ value }}
    </p>
</div>

ng-repeat with Filtering

<input ng-model="search" placeholder="Filter...">
<li ng-repeat="item in items | filter:search">
    {{ item.name }}
</li>