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

2

32

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.

Webster answered 12/6, 2013 at 21:29 Comment(0)
C
52

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

Celestecelestia answered 13/6, 2013 at 7:22 Comment(4)
Thanks. I did not realize you can pass in an array to the orderBy. Guess I overlook that part in the angularjs documentation. But at least I knew there were be an easier way since that would be a pretty common use case.Webster
could you specify a sort order using this method? i.e. I want to sort by group asc then label desc?Clangor
@RossJones Yes, you would change ['group','label'] to ['+group','-label']Celestecelestia
Worked perfectly for me. ThanksPhenacaine
B
1

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.

Barr answered 13/6, 2013 at 1:20 Comment(1)
that actually would not guarantee Group A before Group B. if you have Group A to contain only "GG, HH, II", the order would be reversed. I guess i gave a bad example case. :P. I was actually able to get this to work by sorting by Group first and if the two groups are the same, then sort it by label value.Webster

© 2022 - 2024 — McMap. All rights reserved.