AngularJS - ngOptions: How to order by Group Name and then by Label

T.Ho picture T.Ho · Jun 12, 2013 · Viewed 25.1k times · Source

Let's assume I have the following data array in this form:

var data = [{group:GroupA, label: BB}, {group:GroupB, label: DD}.....].

My binding would be something like:

<select data-ng-options="c as c.label group by c.group for c in data"></select>

I would like the dropdown to list all the items with GroupA before GroupB while having them also sorted under each group.

Something like this:

GroupA
AA
BB
CC

GroupB
DD
EE
FF

I know I can use the orderBy Angular filter, but that doesn't really work the way I need. My guess is I have to write a custom filter that manually orders the list the way I want, but I was wondering if there is an easier way to accomplish the task.

Answer

Dan picture Dan · Jun 13, 2013

orderBy can take an array of multiple parameters to order by. So you can do:

c as c.label group by c.group for c in data | orderBy:['group','label']

Here is a fiddle