Search code examples
angularjsangularjs-ng-repeatpredicateangularjs-orderby

Angular JS - on page load - arranging array in ascending order


Is there a way that I can arrange a simple array like below:

<div ng-init="fruits=['apple','orange','mango','banana','pineapple','kiwi']">

in ascending order on page load

I tried this, but it dint work:

<ul>
<li ng-repeat="fruit in fruits | orderBy:predicate='fruit'">{{fruit}}</li>
</ul>

I'm sure there must be some pretty simple ways but since I'm a novice in Angular, would like help on this.


Solution

  • predicate='fruit' is not a valid orderBy expression (at least not a meaningful one, anyway). To orderBy items in an array as strings, use 'toString()' as the predicate...

    <ul>
        <li ng-repeat="fruit in fruits | orderBy:'toString()'">{{fruit}}</li>
    </ul>
    

    JsFiddle