sharf
sharf

Reputation: 2143

ng-repeat auto sorting incorrectly

I know in my current version of Angular, ng-repeat auto sorts. My problem is that its sorting doesn't appear to be correct.

Taking an object with numbered keys:

{
    "1": "value",
    "2": "value",
    "10": "value"
}

ng-repeat sorts it 1, 10, 2. I'm familiar with this sort of sorting and throwing a 0 on the front of number should fix it. However adding that 0 requires additional code and would need to be stripped out for display.

Likewise, converting to an array caused ng-repeat to loop through all of the empty values (3-9) and creates excess elements, as well as generating a duplicate error.

How can I make ng-repeat sort an object by keys as if they were integers?

Upvotes: 0

Views: 622

Answers (1)

nephiw
nephiw

Reputation: 2046

I was not able to find a solution that didn't change your data structure, but here is an example of how it can be done by using keys to sort the object into an array. Here is the html:

<ul ng-controller="ExampleController">
  <li ng-repeat="item in filtered">{{ item.value }}</li>
</ul>

And here is the code:

  controller('ExampleController', ['$scope', function($scope) {
    $scope.list = {
      "1": "1 Value",
      "10": "10 Value",
      "5": "5 Value",
      "2": "2 Value"
    };

    $scope.$watch('list', function (newVal) {
       $scope.filtered = Object.keys(newVal).map(function (key) {
        return { key: key, value: newVal[key] };
      });
    });
  }]);

The output of this code looks like this:

  • 1 Value
  • 2 Value
  • 5 Value
  • 10 Value

Note that this creates an array of key/value pair objects which is easier to work with. Here is a plunker example of it working: http://plnkr.co/edit/Q0BYLeMzTZmd1k8VzTlQ?p=preview

Upvotes: 1

Related Questions