1

I have a select populated by a key/value object in Angular.

$scope.event_types = {
  "CASE_STATE_CHANGE": "Case state change",
  "NEW_ISSUE": "New Issue",
  "CASE_REVERT": "Case Revert".......}

etc

However when I do an order by, it doesn't work.

<select
     class="form-control"
     name="chase2"
     id="chase2"
     ng-model="eventTypeFilter"
     ng-change="updateEventFilterInput(eventTypeFilter)"
     ng-options="key as value for (key , value) in event_types | orderBy:'value'">

Is this possible with this kind of array?

Paul Stanley
  • 4,018
  • 6
  • 35
  • 56
  • for your array it is working, order by value will keep your array as is, because alphabetically its correct – Pankaj Parkar Feb 19 '15 at 14:23
  • `event_types` is not an array, it's an object. – Omri Aharon Feb 19 '15 at 14:24
  • Question updated, thanks – Paul Stanley Feb 19 '15 at 14:25
  • @Octopi -- No, it's not possible. Your object is not any type of array, it's simply an object, and objects in JS are unordered. There are workarounds (create an array of objects, or a directive that handles this on the fly) - http://stackoverflow.com/questions/25375006/angular-orderby-object-possible – tymeJV Feb 19 '15 at 14:26
  • Thanks, I forget that factoid everytime I dont look at javascript for a week. – Paul Stanley Feb 20 '15 at 10:15

1 Answers1

2

You cannot sort an Object. On most systems it will be sorted alphabetically. If you want to control the order that the elements will be presented you should use an array instead that guarantees ordering.

You could do something like:

   var events_array = Object.keys(event_types)
                            .map(function (key) { return {key: key, value: event_types[key]} })
                            .sort(function(a,b) { return a.key < b.key; } );

and then use events_array on ng-options like:

<select ng-model="eventTypeFilter" 
ng-options="event.key as event.value for event in events_array"></select>

Here is a jsfiddle (need to open console to see the output)

PS: you should consider sorting the values on the controller and then assign to the view as it is much more efficient than ordering on the view

masimplo
  • 3,674
  • 2
  • 30
  • 47