Stop AngularJS ng-repeat rendering in alphabetical order

后端 未结 3 734
抹茶落季
抹茶落季 2021-01-12 20:19

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         


        
相关标签:
3条回答
  • 2021-01-12 20:54

    Object properties don't have a natural order.

    You can achieve what you're looking for with a slightly different Object:

    $scope.data = 
      {
        columns: [
          {
            "EVENT NAME":"Free Event",
            "priority": 0        
          },
          {
            "ORDER_ID":311575707,
            "priority": 1        
          },
          ...
        ]
      }
    
    0 讨论(0)
  • 2021-01-12 20:55

    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?

    0 讨论(0)
  • 2021-01-12 20:59

    A Javascript object does not have the concept of 'natural order' of its keys:

    Definition of an Object from ECMAScript Third Edition (here):

    4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function [...]

    You probably should change a bit your data structure...
    For example:

    $scope.data = 
    {
        1: { "EVENT NAME": "Free Event" },
        2: { "ORDER ID": 311575707 },
        /* ... */
    };
    

    And then use the numerical key to sort your items...

    0 讨论(0)
提交回复
热议问题