I would always prefer using a <div> when designing a basic web page. The <div> element is a lightweight alternative over the <table> element. However, at times you would need to use the <table> to make things simple. You can easily create the headers etc. It’s a matter of choice and both are useful.
👉 How to Push New Elements Inside an ng-repeat Array from AngularJS $scope
Let’s get on with our example.
In the markup section, I created a <table> with the first row as header. Next, I have added a row <tr> with the ng-repeat directive along with the orderBy filter for the field id. I have added the table definitions or <td>, each with an expression (in braces like this -> {{ }}).
👉 Must Read: What is an expression in AngularJS and when should you use it in your application?
<!DOCTYPE html> <html> <head> <title>Example - Bind JSON Data to HTML Table using AngularJS ng-repeat</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <style> table { width: auto; font: 17px Calibri; } table, th, td { border: solid 1px #DDD; border-collapse: collapse; padding: 2px 3px; text-align: center; } </style> </head> <body> <div ng-app="myApp" ng-controller="myController"> <table> <tr> <th>ID</th> <th>Employee Name</th> <th>Date of Joining</th> <th>Age</th> </tr> <tr ng-repeat="emps in empArray | orderBy : 'values.id'"> <td>{{emps.values.id}}</td> <td>{{emps.values.name}}</td> <td>{{emps.joinDate | date : 'dd/MM/yyyy'}}</td> <td>{{emps.values.age}}</td> </tr> </table> </div> </body> <script> angular.module("myApp", []) .controller('myController', ['$scope', function ($scope) { // CREATE AN 'employees' OBJECT, WITH AN ARRAY OF DATA. $scope.employees = { "05/17/2015": { 'id': '001', 'name': 'Alpha', 'age': 37 }, "03/25/2016": { 'id': '002', 'name': 'Bravo', 'age': 27 }, "09/11/2015": { 'id': '003', 'name': 'Charlie', 'age': 29 }, "01/07/2016": { 'id': '004', 'name': 'Delta', 'age': 19 }, "03/09/2014": { 'id': '005', 'name': 'Echo', 'age': 32 } } $scope.empArray = Object.keys($scope.employees) .map(function (value, index) { return { joinDate: new Date(value), values: $scope.employees[value] } } ); } ]); </script> </html>
Inside the controller, I have created an employees object using JSON structure.
👉 I am sure you'll like this post: How to convert JSON data dynamically to HTML table using JavaScript
You can change the order of the table by simply assigning another field using orderBy Filter, such as the joinDate. For example,
<tr ng-repeat="emps in empArray | orderBy : 'joinDate'">
Or, using the name field. Like this,
<tr ng-repeat="emps in empArray | orderBy : 'values.name'">
👉See this Demo
ID | Employee Name | Date of Joining | Age |
---|---|---|---|
{{emps.values.id}} | {{emps.values.name}} | {{emps.joinDate | date : 'dd/MM/yyyy'}} | {{emps.values.age}} |
For more interesting features: Check this post here, if you want to show JSON data in descending or ascending order.