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?

5
  • for your array it is working, order by value will keep your array as is, because alphabetically its correct Commented Feb 19, 2015 at 14:23
  • event_types is not an array, it's an object. Commented Feb 19, 2015 at 14:24
  • Question updated, thanks Commented Feb 19, 2015 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) - stackoverflow.com/questions/25375006/… Commented Feb 19, 2015 at 14:26
  • Thanks, I forget that factoid everytime I dont look at javascript for a week. Commented Feb 20, 2015 at 10:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.