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

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Method 2

It seems like orderBy would work exactly like you want.

Just take your expression and add the orderBy at the end:

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

This will first order the data array by the value of each item’s label property, and then group them. Because the data will have been ordered correctly, each group will show up sorted correctly.

Here’s a fiddle.

Note how the initial array is defined in backwards order, but is sorted correctly in each group in the select.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply