AngularJS ngOptions sort array
Asked Answered
P

2

26

I have been trying to use ng-options to display an array of fonts in a select sorted alphabetically by the value of the items in the array.

HTML

<select ng-options="font for font in webfonts | orderBy:'font'" name="fonts">
     <option value="">Choose a font</option>
</select>

JS

$scope.webfonts = [ 
        'Abel', 'Crafty Girls' , 'Lato' , 'Average',
        'Corben', 'Quicksand', ... ];

I've tried changing the value in orderBy and other things. I've read through the documentation and all comments.

What am I missing? Is this supposed to only work on objects?

Plastid answered 15/8, 2013 at 20:10 Comment(0)
S
53

This is what you need to do:

<select ng-model="selected" ng-options="font for font in webfonts | orderBy:'toString()' " name="fonts">
  1. You need to add ng-model to correctly make the binding works for a list of strings.
  2. You can use toString() to sort if the input contains a list of strings. Since the expression of orderBy can be a Getter function. The result of this function will be sorted using the <, =, > operator.

Demo

Sadyesaechao answered 15/8, 2013 at 20:41 Comment(2)
@ChrisB Because toString() is available in any string object in the prototype. This is indeed a trick, and it deserves to keep in mind forever.Sadyesaechao
It works because .toString() is a property of the string in the array webfonts, and orderBy is expecting a property of the object given (font). At the same time toString() returns the value of font which happens to be exactly what I want to order by. Is this right? Am I understanding it correctly?Plastid
B
4

As the documentation specifies, the string argument is for object properties, not for primitives. I think, as elementary as it sounds, you have to create a function on the scope that simply returns the argument, and pass that to orderBy.

See jsFiddle!

Berg answered 15/8, 2013 at 20:33 Comment(1)
As the documentation specifies, you can pass a function name and the result of it is used as the comparison value!Easton

© 2022 - 2024 — McMap. All rights reserved.