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

StackOverflow https://stackoverflow.com/questions/20884097

  •  23-09-2022
  •  | 
  •  

質問

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)

役に立ちましたか?

解決 2

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;
    }
}

他のヒント

ng-options adds empty option if case if value currently bound by ng-model doesn't exist in list of options. This prevents from overwriting value due bounding to empty select (this is an often problem in for example knockoutjs).

Clicking option group clears selection and empty option added. You can see it if add debug <div>{{selTemplates}}</div> below select list. Also even static select with size or multiple attribute specified clears its selection on clicking option. If size is omitted (for regular dropdown) clicking optgroup doesn't clears selected value.

I'm not sure if this browser inconsistence or expected behavior (if you said it works in IE) but consider replacing select with custom HTML emulates list selection.

Add ng-init="selTemplates=userTemplates[0]" in your <select> You can remove "$scope.selTemplates = ***" in your controller

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top