How to sort array in ng-options by key?

24,944

Solution 1

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

Solution 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'"

Solution 3

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

Share:
24,944
Faud
Author by

Faud

Updated on July 17, 2022

Comments

  • Faud
    Faud almost 2 years

    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.

  • Faud
    Faud almost 9 years
    I get empty select list by your solution
  • Pankaj Parkar
    Pankaj Parkar almost 9 years
    @Faud try adding single ' on key as @solid_luffy said
  • Faud
    Faud almost 9 years
    Also is same. Not working. I get error: Error: $parse:lexerr Lexer Error
  • Faud
    Faud almost 9 years
    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=Untermin‌​ated%20quote&p1=s%20‌​3-4%20%5B'%5D&p2=key‌​'
  • Pankaj Parkar
    Pankaj Parkar almost 9 years
    @Faud could you accept mine answer..I'll give you working fiddle/plunkr
  • Pankaj Parkar
    Pankaj Parkar almost 9 years
    @Faud check the plunkr which I've added..Thanks