In this article I will explain with an example, how to use AngularJS ng-repeat directive to populate (bind) HTML Table from JSON array.
First an array of JSON objects is generated and then it is used to populate (bind) HTML Table using the AngularJS ng-repeat directive.
Populate (Bind) dynamic HTML Table from JSON using ng-repeat in AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Button and Table which will be populated from JSON array using ng-repeat directive.
The Button has been assigned ng-click directive. When the Button is clicked, the GenerateTable function of the Controller gets called.
Inside the GenerateTable function, an array of JSON objects is created and assigned to the Customers JSON array.
The ng-repeat directive as the name suggests repeats the element based on the length of the collection, in this scenario it will repeat the TR element (HTML Table Row).
The TBODY element of the HTML Table has been assigned ng-repeat directive in order to iterate through all the items of the Customers JSON array.
For each JSON object in the Customers JSON array, a TR element (HTML Table Row) is generated and appended into the HTML Table.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.IsVisible = false;
$scope.GenerateTable = function () {
$scope.Customers = [
{ CustomerId: 1, Name: "John Hammond", Country: "United States" },
{ CustomerId: 2, Name: "Mudassar Khan", Country: "India" },
{ CustomerId: 3, Name: "Suzanne Mathews", Country: "France" },
{ CustomerId: 4, Name: "Robert Schidner", Country: "Russia" }
];
$scope.IsVisible = true;
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Generate Table" ng-click="GenerateTable()" />
<hr />
<table cellpadding="0" cellspacing="0" ng-show="IsVisible">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.CustomerId}}</td>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads