ngN00b: looping $index

protip example

by joseym

HTML

<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-controller="MainCtrl">
    <h1>{{ title }}</h1>
    <hr />
    <p class="alert alert-info">
        This is the working example for the ngN00b protip.
    </p>
    <hr />
    <h4>Array loop</h4>
    <ul class="list">
        <li ng-repeat="item in arrayItems"><span class="label label-info">{{ $index }}</span> - {{ item }}</li>
    </ul>
    <hr>
    <h4>Hash (object) loop</h4>
    <ul class="list">
        <li ng-repeat="val in hashItems"><span class="label label-info">{{ $index }}</span> - {{ val }}</li>
    </ul>
    <hr>
    <h4>(key, value) on hashes</h4>
    <ul class="list">
        <li ng-repeat="(key, val) in hashItems"><span class="label label-info">{{ $index }}</span> - <strong>{{ key }}</strong> == {{ val }}</li>
    </ul>
</div>

CSS

body { margin: 15px; }

JavaScript

var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
    $scope.title = 'ngN00b: looping $index';
    
    $scope.arrayItems = ['Item 1', 'Item 2', 'Item 3'];
    $scope.hashItems = {
        'first' : 'Item 1',
        'second' : 'Item 2',
        'third' : 'Item 3'
    }
    
});