Thursday 16 June 2016

Angular.js Helper Variables in ng-repeat

<html ng-app="notesApp">
<head><title>Notes App</title></head>
<body ng-controller="MainCtrl as ctrl">
<div ng-repeat="note in ctrl.notes">
<div>First Element: {{$first}}</div>
<div>Middle Element: {{$middle}}</div>
<div>Last Element: {{$last}}</div>
<div>Index of Element: {{$index}}</div>
<div>At Even Position: {{$even}}</div>
<div>At Odd Position: {{$odd}}</div>
<span class="label"> {{note.label}}</span>
<span class="status" ng-bind="note.done"></span>
<br/><br/>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js">
</script>
<script type="text/javascript">
angular.module('notesApp', [])
.controller('MainCtrl', [function() {
var self = this;
self.notes = [
{id: 1, label: 'First Note', done: false},
{id: 2, label: 'Second Note', done: false},
{id: 3, label: 'Done Note', done: true},
{id: 4, label: 'Last Note', done: false}
];
}]);
</script>
</body>
</html>

OUTPUT

First Element: true
Middle Element: false
Last Element: false
Index of Element: 0
At Even Position: true
At Odd Position: false
First Note false
First Element: false
Middle Element: true
Last Element: false
Index of Element: 1
At Even Position: false
At Odd Position: true
Second Note false
First Element: false
Middle Element: true
Last Element: false
Index of Element: 2
At Even Position: true
At Odd Position: false
Done Note true
First Element: false
Middle Element: false
Last Element: true
Index of Element: 3
At Even Position: false
At Odd Position: true
Last Note false 

Explation:
In this example, we use the same array that we did in the example with the ng-repeat
over the array of items. The only difference is that we now display more state about the
item being repeated in the HTML. For each item, we display which index the item is in,
and whether it is the first, middle, last, odd, or even item.


No comments:

Post a Comment