In the previous angularjs article have explained how to delete table row in angularjs where we use a $index to get the index number.
Ng-Repeat has $index property which iterator offset of the repeated element (starts from 0). So by using $index we able to display serial number ( unique number id )
Step to display serial number (index number) using ng-repeat.
- Setup: Download and import AngularJS file.
- Create JSON data
- Html Markup: Add table ( using ng-repeat to bind data)
Output:
# Setup: Download and import AngularJS file.
You can download AngularJS files from angularjs.org, or you can use Google hosted files. After importing Angularjs file, add Directive ng-app & ng-controller to the body tag.
So now our HTML markup looks like as shown below
<html>
<head>
<script src="angularjs/angular.min.js" type="text/javascript"></script>
</head>
<body ng-app="myapp" ng-controller="tableController">
</body>
<html>
# Create JSON data
Here we have a list of employees info into variable employees, which displays name, gender, city. Code as written below.
var app = angular.module("myapp", []);
app.controller("tableController", ['$scope', function ($scope) {
$scope.employees = [{ 'Name': 'Satinder Singh', 'Gender': 'Male', 'City': 'Bombay' },
{ 'Name': 'Leslie Mac', 'Gender': 'Female', 'City': 'Queensland' },
{ 'Name': 'Andrea ely ', 'Gender': 'Female', 'City': 'Rio' },
{ 'Name': 'Amit Sarna', 'Gender': 'Male', 'City': 'Navi Mumbai' },
{ 'Name': 'David Miller', 'Gender': 'Male', 'City': 'Scouthe'}];
} ]);
Try It Yourself ⇒
#HTML Markup: Add table ( using ng-repeat to bind data)
Here first we add an HTML Table and using ng-repeat we bind our JSON data to it. Now using $index + 1 we able to display serial number to each row. Note here we added + 1 to $index so that the numbers start from 1 instead of 0. By default $index starts from 0, if you want to starts from 0 then directly use the $index.
Final code look like as written below
<table class="table table-stripe" >
<thead><tr>
<th>Sr no</th>
<th>Name</th>
<th>Gender</th>
<th> City </th>
</tr></thead>
<tbody>
<tr ng-repeat="emp in employees">
<td> {{$index + 1}}</td>
<td> {{ emp.Name }} </td>
<td> {{emp.Gender }} </td>
<td> {{emp.City }}</td>
</tr>
</tbody>
</table>
Conclusion: At the end of this article we learned how to add the serial number to a table using ng-repeat in AngularJs. That’s how to use ng-repeat directive $index property to set index Number with an example. Basically, we added the serial number in our HTML table column using ng-repeat.
You must also like this:
- How to Bind JSON data to HTML Table [AngularJs]
- How to Delete Table Row tr on button click in AngularJS
- How to access nested JSON object in AngularJs using ng-repeat
Other Reference: