How to sort array in ng-options by key?
Asked Answered
R

3

12

There is such array:

month: Array[13]0: "M"1: "January"2: "February"3: "March"4: "April"5: "May"6: "June"7: "July"8: "August"9: "September"10: "October"11: "November"12: "December"

I do:

ng-options="key as value for (key, value) in data.month | orderBy:key"

But I get unsorted select list.

Rhenium answered 3/6, 2015 at 13:8 Comment(1)
The array is already in calendar order, why are you sorting it?Leopard
S
17

In order to use tracking with filters use track by.

Markup

ng-options="key as value for (key, value) in data.month | orderBy:'key' track by key"

Update

This orderBy will never work because you are having literal array. You need to convert this array to JSON like object which would structured like [{id: 0, value: "M"}, {id: 1, value: "January"},......]

HTML

ng-options="item.id as item.value for items in data.month | orderBy:'id'"

Demo Plunkr

Sombrero answered 3/6, 2015 at 13:10 Comment(7)
I get empty select list by your solutionRhenium
@Rhenium try adding single ' on key as @solid_luffy saidSombrero
Also is same. Not working. I get error: Error: $parse:lexerr Lexer ErrorRhenium
I have format : "day":[{"id":1,"value":1},{"id":2,"value":2} but get empty list with error: Error: [$parse:lexerr] http://errors.angularjs.org/1.3.13/$parse/lexerr?p0=Unterminated%20quote&p1=s%203-4%20%5B'%5D&p2=key'Rhenium
@Rhenium could you accept mine answer..I'll give you working fiddle/plunkrSombrero
@Rhenium check the plunkr which I've added..ThanksSombrero
The plunkr is an ng-repeat; similar but not what this question asks. 😕 Also did you mean item.id as item.value for items in your html template snippet or item.id as item.value for item (no s on final item)?Davie
T
2

Your missing two ''s. This part, orderBy: key should be orderBy:'key'

Try this:

ng-options="key as value for (key, value) in data.month | orderBy: 'key'"
Trunks answered 3/6, 2015 at 13:12 Comment(0)
R
1

To resolve this issue need reformat ng-option like as:

day.id as day.value for day in data.month

And array data.month would be how as told user pankajparkar

Rhenium answered 3/6, 2015 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.