AngularJS select has empty value

A quick post to understand why AngularJS adds a empty value at the beginning of your select box.

Let’s say you have this code.

<select class="form-control" ng-model="selectedBook" ng-options="book.id as book.title for book in books"></select>

This might generate something like:

<select class="form-control" ng-model="selectedBook" ng-options="book.id as book.title for book in books">
	<option value="?" selected="selected"></option>
	<option value="0">Title Book #1</option>
	<option value="1">Title Book #2</option>
	<option value="2">Title Book #3</option>
</select>

Why do you get an option with a value ? and no text inside?

It’s because your model selectedBook isn’t initialized with a valid value or, in this case, isn’t initiliazed at all. In order to not select a default actual value, AngularJS generates a empty option and selects it by default.

###How to fix it?

<select class="form-control" ng-model="selectedBook" ng-options="book.id as book.title for book in books" ng-init="selectedBook=0"></select>

In this code we specify a initial value for selectedBook. It will generates this:

<select class="form-control" ng-model="selectedBook" ng-options="book.id as book.title for book in books" ng-init="selectedBook=0">
	<option value="0" selected="selected">Title Book #1</option>
	<option value="1">Title Book #2</option>
	<option value="2">Title Book #3</option>
</select>

Note that ng-init allows functions. So you could call a function initSelect() which could wait for another value to initialize selectedBook or whatever :)

You can find a JSFiddle for this article here And this article is inspired by this stackoverflow answer