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>

AngularJS: Images failing to load (Not Found) with curly brackets in URL

This is one of those schoolboy errors that, in hindsight, is blindingly obvious and I should have been able to work out for myself, but required a bit of searching before I managed to ask Google (other search providers are available) the right question.

Basically, I had a load of image src paths that were defined using AngularJS expressions, e.g.

<img src="content/images/results/{{result.id}}.jpg" />

The images loaded fine, but I kept getting 404 (Not Found) errors on image URLs that contained the curly brackets of my expressions (/content/images/results/%7B%7Bresult.id%7D%7D.jpg). This seemed like it was because the page was trying to load the images before Angular has done it’s work and converted the expressions into sensible URLs. And that’s exactly the problem!

The solution is a simple one: use ng-src instead of src if the URL has an expression in it, e.g.

<img ng-src="content/images/results/{{result.id}}.jpg" />