19

I have an object that looks like this:

{
    "03" : "Apple",
    "02" : "Banana",
    "01" : "Cranberry"
}

and it orders it by the keys (which makes sense) in my ng-repeat. This results in the labels being out of alphabetical order ("cranberry" being first). How do I make it so that it orders my repeater by the values (alphabetically)?

I can supply it in the order I want to the ng-repeat, but it sorts it by the key. If I could make it not do that, then that would also work.

2
  • Is there anything stops you from sorting the data in controller? Commented May 29, 2013 at 21:35
  • 2
    I don't know the answer, but i do know that supplying the object pre-sorted won't work, because JS engines are not obliged to maintain the order of properties in an object. Commented May 29, 2013 at 21:36

1 Answer 1

28

To sort array in ngRepeat you can use orderBy filter but it works only with arrays, so you should use array in ngRepeat.

It will be something like this in controller:

$scope.myData = [
    {
        key:    "01",
        value:  "Cranberry"
    },
    {
        key:    "02",
        value:  "Banana"
    },
    {
        key:    "03",
        value:  "Apple"
    }
];

and in html:

<div class="item" ng-repeat="item in myData|orderBy:'value'">{{item.value}}</div>
Sign up to request clarification or add additional context in comments.

2 Comments

But if you realy want to use object in scope you can create a filter that convert an object into array.
There was no particular need to use an object so I used the method you suggested and it's working great. Thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.