In my angular app I'm trying to display JSON data in a table. The data looks like this:
$scope.data =
{
"EVENT NAME":"Free Event",
"ORDER ID":311575707,
"DATE":"6/26/14",
"GROSS REVENUE (USD)":"0",
"TICKET REVENUE (USD)":"0",
"EVENTBRITE FEES (USD)":"0",
"CC PROCESSING (USD)":"0",
"TICKETS":1,
"TYPE":"Free Order",
"STATUS":"Free Order",
"TRANSACTION ID":"",
"NOTES":"",
"FIRST NAME":"Khee Seng",
"LAST NAME":"Chua",
"EMAIL ADDRESS":"[email protected]"
};
And I'm displaying it like this:
<table class="table table-striped selector">
<tbody>
<tr>
<td ng-repeat="(key, value) in data">
<strong>{{key}}</strong>
</td>
</tr>
<tr>
<td ng-repeat="(key, value) in data">
{{value}}
</td>
</tr>
</tbody>
</table>
In my mind this should go through each `(key, value) pair in the object and display it in order. However, AngularJS displays the values in alphabetical order.
Here's a plunkr which replicates this issue: http://plnkr.co/edit/V3Y2ZuwV1v9Pzsl0jGhA?p=preview
How can I tweak the code so it displays in the natural order that the object actually comes in?
You can achieve it like this
Working Demo
In the scope define a method like as shown
$scope.notSorted = function(obj){
if (!obj) {
return [];
}
return Object.keys(obj);
}
and in html like as shown below
html
<table class="table table-striped selector">
<tbody>
<tr>
<th ng-repeat="key in notSorted(data)">
{{key}}
</th>
</tr>
<tr>
<td ng-repeat="key in notSorted(data)" ng-init="value = data[key]">
{{value}}
</td>
</tr>
</tbody>
</table>
Original Article: ng-repeat with no sort? How?
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