Search code examples
javascriptangularjsangularjs-filterng-optionsangularjs-orderby

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


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.


Solution

  • 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