Search code examples
javascriptangularjsng-optionsangularjs-ng-options

Is it possible to mix elements in ng-options with and without groups?


Until angular 1.4.4 (or possibly a bit further) it was possible to use groups in ng-options in a way that if the group name was an empty string or null/undefined, it created an option outside groups. Is there any way to do this in the new version 1.5.7? According to this question, the accepted answer suggests adding a new group to collect all the non-group elements, but that doesn't suit my specifications. I certainly need an option at the beginning that doesn't belong to a group, and after that the elements within groups, which still works fine after migrating to the new version.

Here is the fiddle for the linked question, where I want to get rid of the group that is named No_Group in that example.

ng-options="d.title group by (d.group ==='' ? 'No_Group' : d.group) for d in 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"
        }
]

Solution

  • Turns out that I need to feed undefined as the group, empty string or null doesn't work anymore. One option is to write the html part as follows:

    ng-options="d.title group by (d.group ? d.group : undefined) for d in data"
    

    But since I know which objects will be outside the group, I resolve the issue more elegantly by not adding them the group object at all, which would correspond to the following in this example code:

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

    Check out the issue responsible for this behavior.