Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
4 views
in Web Technology by (47.6k points)

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 the 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?

1 Answer

+2 votes
by (106k points)

The reason why AngularJS include an empty option in select is that it is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. Also, this prevents 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;

Related questions

0 votes
1 answer
0 votes
1 answer
+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...