Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 322
Kevin Beal Avatar asked May 29 '13 21:05

Kevin Beal


People also ask

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What is orderBy in AngularJS?

Definition and Usage The orderBy filter allows us to sort an array. By default, strings are sorted alphabetically, and numbers are sorted numerically.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

Where is the last element in NG-repeat?

You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .


1 Answers

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>
like image 182
ardentum-c Avatar answered Oct 06 '22 14:10

ardentum-c