AngularJS: labelled empty option in select box when using ng-options

I’m using ng-options to generate the options for select boxes in AngularJS. By default, when a selected value is not defined, Angular adds a blank option, without a label. I wanted to give this blank option a label, e.g. “Select something”, but couldn’t see how to do it.

Not surprisingly it’s very easy, and is actually mentioned in the docs (https://docs.angularjs.org/api/ng/directive/select – 4th paragraph, beginning “Optionally” at time of writing), but like, I guess, most people, I never read the docs properly and just scanned the examples, which don’t show this.

All you need to do is add the labelled blank option in the select box, as you normally would if you were just writing the HTML, e.g.:

<select name="myselect" ng-model="MyCtrl.selected" 
   ng-options="option.value as option.label for option in MyCtrl.options">
   <option value="">Select something</option>
</select>

Angular will then generate the remaining options from the options array that you pass to it, and leave the blank option at the top.

In the above example, to not show a blank option at all, remove the option tag and set Ctrl.selected to be equal to the value that you want to be selected by default in the controller, e.g.

In controller.js

this.options = [ { value: 1, label: 'Yes' }, { value: 0, label: 'No' } ];
this.selected = 1;

In view.html

<select name="myselect" ng-model="MyCtrl.selected" 
   ng-options="option.value as option.label for option in MyCtrl.options">
</select>