dkc007 dkc007 - 28 days ago 20
AngularJS Question

Dynamic table creation with ng-repeat in angularjs

I want to generate dynamic table with dynamic table header and row/columns according to json object comes from webapi.

enter image description here

Here are examples of json object which comes every time different.

[
{"Country":"Australia","Toner Quantity":8},
{"Country":"China","Toner Quantity":6},
{"Country":"India","Toner Quantity":11},
{"Country":"South Korea","Toner Quantity":1}
]


and some time it comes like

[
{"CustomerName":"FORD","Australia":0,"China":2,"India":0,"South Korea":0},
{"CustomerName":"ICICI PRUDENTIAL","Australia":0,"China":0,"India":5,"South Korea":0},
{"CustomerName":"Kimberly Clark","Australia":0,"China":0,"India":0,"South Korea":1},
{"CustomerName":"McDonalds","Australia":1,"China":0,"India":0,"South Korea":0},
{"CustomerName":"Novartis","Australia":1,"China":0,"India":0,"South Korea":0},
{"CustomerName":"Origin Energy","Australia":3,"China":0,"India":0,"South Korea":0}
]


So I have tried but not able to achieve dynamic table with headers and row/columns

my html code like

<table class="table striped">
<thead>
<tr role="row">
<th ng-repeat="th in dataconfigureListData.previewData">{{th}}</th>
</tr>
</thead>
<tbody>
<tr role="row" data-ng-repeat="previewData in dataconfigureListData.previewData">
<td> {{previewData.Country}}</td>
<td> {{previewData['Total Toner Qty']}}</td>
</tr>
</tbody>
</table>

Answer

You can do this by using an ng-repeat inside another. And also, use the first line to render the headers.

The following snippet implements this solution.

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.myArray = [{
      "CustomerName": "FORD",
      "Australia": 0,
      "China": 2,
      "India": 0,
      "South Korea": 0
    }, {
      "CustomerName": "ICICI PRUDENTIAL",
      "Australia": 0,
      "China": 0,
      "India": 5,
      "South Korea": 0
    }, {
      "CustomerName": "Kimberly Clark",
      "Australia": 0,
      "China": 0,
      "India": 0,
      "South Korea": 1
    }, {
      "CustomerName": "McDonalds",
      "Australia": 1,
      "China": 0,
      "India": 0,
      "South Korea": 0
    }, {
      "CustomerName": "Novartis",
      "Australia": 1,
      "China": 0,
      "India": 0,
      "South Korea": 0
    }, {
      "CustomerName": "Origin Energy",
      "Australia": 3,
      "China": 0,
      "India": 0,
      "South Korea": 0
    }];
  });

angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});
table {
  border-collapse: collapse;
}
td,
th {
  padding: 2px 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<table ng-controller="myController" border="1">
  <tr>
    <th ng-repeat="(key, val) in myArray[0]">{{ key }}</th>
  </tr>
  <tr ng-repeat="row in myArray">
    <td ng-repeat="column in row">
      {{ column }}
    </td>
  </tr>
</table>