Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop AngularJS ng-repeat rendering in alphabetical order

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?

like image 562
JVG Avatar asked Jul 09 '14 14:07

JVG


1 Answers

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?

like image 139
Nidhish Krishnan Avatar answered Sep 22 '22 12:09

Nidhish Krishnan