Thursday, 1 September 2016

Why does AngularJS include an empty option in select?



I've been working with AngularJS for the last few weeks, and the one thing which is really bothering me is that even after trying all permutations or the configuration defined in the specification at http://docs.angularjs.org/api/ng.directive:select, I still get an empty option as the first child of select element.




Here's the Jade:



select.span9(ng-model='form.type', required, ng-options='option.value as option.name for option in typeOptions');


Here the controller:



$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },

{ name: 'Enhancement', value: 'enhancement' }
];


Finally, here's the HTML which gets generated:






What do I need to do to get rid of it?



P.S.: Things work without this as well, but it just looks odd if you use select2 without multiple selection.


Answer



The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.




If you want to get rid of the empty option just select an initial value in your controller, something like:



$scope.form.type = $scope.typeOptions[0].value;


Here is the jsFiddle: http://jsfiddle.net/MTfRD/3/



In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...