Kevin Beal
Kevin Beal

Reputation: 10849

AngularJS - How to orderBy the value of an array-like object in an ng-repeat

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.

Upvotes: 19

Views: 24495

Answers (1)

ardentum-c
ardentum-c

Reputation: 1410

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>

Upvotes: 28

Related Questions