Search code examples
javascriptangularjsng-options

Angularjs: ng-options: How to order options with group and non-group


I have my group by ng-options looks like this

    <select ng-model="selected" ng-options="d.title group by d.group for d in data"></select>

Here is my data

$scope.data = [
    {
        group:"",
        title:"No GroupA"
    },
    {
        group:"Group_1",
        title:"1"
    },
    {
        group:"",
        title:"No GroupB"
    },
    {
        group:"Group_2",
        title:"2"
    },
    {
        group:"",
        title:"No GroupC"
    }
];

the problem is that this creates the optgroup on the bottoms of this select menu, not the order as same as my data list.

No GroupA
No GroupB
No GroupC
[Group_1]
 1
[Group_2]
 2

i want to produce:

No GroupA
[Group_1]
 1
No GroupB
[Group_2]
 2
No GroupC

Here is Fiddle

Thanks!


Solution

  • As far as I know, you can't have a mixed select - options within and without groups.

    You could create a generic group for these options:

    <select ng-model="selected" 
            ng-options="d.title group by (d.group ==='' ? 'No_Group' : d.group) for d in data">
    </select>
    

    Here is your updated fiddle.