Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Automatic ordering from ng-repeat

I have a json object. It is not ordered in ascending order.

 $scope.myData = {
        "MAX" : "some value",
        "Forms" : "some value",
        "Grids And Tables" : "some value",
        "Navigation" : "some value",
        "Services & APIs" : "some value"
  }

I used ng-repeat for showing it in my html template. I got the result but, the order has changed in to ascending order.

Forms
Grids And Tables
MAX
Navigation
Services & APIs

How to prevent angular js from automatic ordering?

Check this link

like image 343
Sajith Avatar asked Dec 10 '13 06:12

Sajith


2 Answers

As suggested, it's not possible to sort object keys. Buy you can sort over an array created using those object keys -

$scope.keys = Object.keys($scope.myData);
<ul>
  <li ng-repeat="key in keys">
    {{key}} - 
    {{myData[key]}}
  </li>
</ul>
like image 63
Mukesh Soni Avatar answered Oct 21 '22 01:10

Mukesh Soni


The order of iterating over object keys in javascript is technically undefined. While most browsers will iterate over the object in the defined order, you should not rely on this behavior.

In the case of angular, ng-repeat needs to always sort the keys so that order is deterministic even when keys are added after the fact. It is not possible to change this behavior because it would break the directive as keys are added or removed dynamically.

If you need to rely on the ordering of your data, then an object hash is not the correct data structure. You should either re-format your data as an array, or simply create a separate array with the order of the keys and do your ng-repeat over it. Using the keys to index into the object.

like image 2
Daniel Tabuenca Avatar answered Oct 20 '22 23:10

Daniel Tabuenca