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:
<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" class="span9 ng-pristine ng-invalid ng-invalid-required">
<option value="?" selected="selected"></option>
<option value="0">Feature</option>
<option value="1">Bug</option>
<option value="2">Enhancement</option>
</select>
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.
Among the multitudes of answers here, I figured I'd repost the solution that worked for me and met all of the following conditions:
value=""
)code
src
original q&a - https://stackoverflow.com/a/32880941/1121919
A quick solution:
Hope it helps someone. Ideally, the selected answer should be the approach but if in case that's not possible then should work as a patch.
This worked for me
If you want an initial value, see @pkozlowski.opensource's answer, which FYI can also be implemented in the view (rather than in the controller) using ng-init:
If you don't want an initial value, "a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent null or "not selected" option":
Something similar was happening to me too and was caused by an upgrade to angular 1.5.
ng-init
seems to be being parsed for type in newer versions of Angular. In older Angularng-init="myModelName=600"
would map to an option with value "600" i.e.<option value="600">First</option>
but in Angular 1.5 it won't find this as it seems to be expecting to find an option with value 600 i.e<option value=600>First</option>
. Angular would then insert a random first item:Angular < 1.2.x
Angular > 1.2
I would like to add that if the initial value comes from a binding from some parent element or 1.5 component, make sure that the proper type is passed. If using
@
in binding, the variable passed will be string and if the options are eg. integers then the empty option will show up.Either parse properly the value in init, or binding with
<
and not@
(less recommended for performance unless necessary).