Search code examples
angularjsng-options

ng-options creates an empty option at the end when listbox group heading is clicked


I am stuck on this particular issue with ng-options. I am creating a listbox with option grouping:

<select ng-model="selTemplates" size="3" style="width: 150px" 
ng-options="template.Name group by template.Type for template in userTemplates">
</select>

When I click on a group heading (Type1 or Type2), Chrome creates an empty option at the end and marks it selected. I believe it has something to do with the selection because it may not find anything 'selected' when a header is clicked, but an empty value at the bottom is not desired.

Please see the fiddle here.How can i fix it?

(The code works fine in IE9, although not sure why the fiddle doesn't)


Solution

  • Looks like inconsistent browser implementation is the reason. On clicking option header, Chrome clears out the selection whereas IE doesn't, that's why Chrome inserts a new empty row at the bottom.

    As a workaround, I am saving last selected value in a variable, and in case user clicks on header (which will make selection null), I am restoring the last selection. See fiddle. Not exactly pretty, but gets the work done.

    $scope.checkSelection = function() {
         if ($scope.selTemplates == null) {
            $scope.selTemplates = last;
        }
        else {
            last = $scope.selTemplates;
        }
    }