Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

ng options - AngularJS ngOptions sort array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...