JSON is a lightweight data-interchange platform. During development sometimes we required to bind JSON file data to controls. In this session I am showing how to create a table in AngularJS using JSON data. Here I have 2 files one is AngularJS-table.htm & insured.json. insured.json is the JSON file which contains data for insured members of my family. In AngularJS-table.htm file I am showing all the members name & their relationship with me in tabular structure.
Trick I used here to bind data is so simple. Using AngularJS $http.get() method I am fetching data from insured.json file. Over success I am getting all JSON file data in response object. Then to bind these data in HTML table I am assigning response.insureds (parent node of JSON data) to $scope.members object. In HTML I have a table which contains two rows header & a dynamic row. Header I defined manually but for the next row I am using ng-repeat directive of AngularJS. During execution according to the number of records ng-repeat will generate that number of rows for the table. To display this table more professional here I used CSS styles.
AngularJS-table.htm
<!DOCTYPE html> <html ng-app="myInsured"> <head> <title>Example to display JSON data in a Table using AngularJS?</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script> <script type="text/javascript"> var myInsured = angular.module('myInsured', []); myInsured.controller('insuredCtrl', function($scope, $http) { $http.get("insured.json").success(function (response) { /*After Successfully fetch the data from JSON file assigning these data to $scope object variable*/ $scope.members = response.insureds; }); }); </script> <style type="text/css"> /*Style for Table*/ table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 4px; font-family: arial; } /*Style for Table Header*/ th { background: darkblue; color: white; text-align: left; } /*Style for Alternate Rows*/ table tr:nth-child(odd) { background-color: #C2EBC3; } table tr:nth-child(even) { background-color: #FFFFFF; } </style> </head> <body ng-controller="insuredCtrl"> <table> <tr> <th>Name</th> <th>Relationship</th> </tr> <tr ng-repeat="indivisual in members"> <td>{{ indivisual.Name }}</td> <td>{{ indivisual.Relation }}</td> </tr> </table> </body> </html>
insured.json
{"insureds": [ { "Name": "Aparmita Dash", "Relation": "Spouse" }, { "Name": "Angurbala Dash", "Relation": "Mother" }, { "Name": "Surendra Dash", "Relation": "Father" }, { "Name": "Nirupama Dash", "Relation": "Daughter" }, { "Name": "Sanjarekha Dash", "Relation": "Daughter" } ] }