From a web service I am getting a JSON string. It may vary based on the request. 2 JSON result are
Result 1
[
{
"Key": 1,
"ID": 1,
"applicationId": "1",
"applicationName": "APP1"
},
{
"Key": 2,
"ID": 1,
"applicationId": "2",
"applicationName": "APP2"
}
]
Result 2
[
{
"OrgKey": 1,
"ID": 1,
"OrgID": "1",
"OrgName": "Org1"
},
{
"OrgKey": 2,
"ID": 4,
"OrgID": "6",
"OrgName": "Org2"
}
]
How will I display this in a table?
In controller js file I use the $http.get
method and in Success method I put
$scope.resultData = data;
But in HTML how I will display the dynamic contents?
<table>
<thead>
<tr>
<th ng-repeat = "result in resultData">
<!-- Not the right way -->
<!-- Here I want to put the headers like "Key,ID" ... -->
</th>
</tr> </thead>
<tbody>
<tr ng-repeat = ""result in resultData">
<td> {{result.Key }} </td>
<!-- When the firlds vary, how to put? ->
</tr>
</tbody>
</table>
Is it possible? If so How? Thanks.
first of all you should get first row to set your table's header like this
<thead>
<tr>
<th ng-repeat="(header, value) in resultData[0]">
{{header}}
</th>
</tr>
</thead>
after this for your tbody
you should get your rows first then inside the row travel all cells,
<tbody>
<tr ng-repeat="row in resultData">
<td ng-repeat="cell in row">
{{cell}}
</td>
</tr>
</tbody>
here is working PLUNKER...
UPDATE
some users asked for if this can be handle without sorting headers and their values...
the answers is yes but before starting you should know why it is already sorted alphabetacally...
angular ng-repeat
directive works differentlly with arrays and objects... If you use array you can make it sortable but this is not an option for objects here is a discussion about it...
so right now best way is pushing object values into array before we use them in ng-repeat..
here is second PlUNKER
NOTE : You will see I remove $$hashKey from array, because they are not a property of original element, angular add them into object automatically to watch changes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With