Andrew Piliser Andrew Piliser - 3 months ago 10
AngularJS Question

Angular Select with an option value of space

I have a

<select>
with an
ng-model
, and one of the options is a space. When the initial value is something else, angular selects the right option, but when the initial value is a space, angular adds the empty option.

I can reproduce it with html like:

<select ng-model="a" ng-trim="false">
<option value=" ">Default</option>
</select>

<select ng-model="b">
<option value="x">Default</option>
</select>


and a controller like:

$scope.a = " ";
$scope.b = "x";


The first select will have a blank option and the second will show "Default". Adding
ng-trim
doesn't seem to help, and I'm getting the values from a database so I can't easily change them.

I can reproduce the issue with Angular 1.4.8, 1.4.9 (which I'm using) and 1.5.8, all from https://code.angularjs.org/.

I have a fiddle here: https://jsfiddle.net/d1cj3kzb/4/.

How can I get the
<select>
to show the correct option when
ng-model
is initialized to a space?

Answer

Try declaring a variable in your code that has the value of your default, in this case space, like:

$scope.spaceChar = " ";

and then in your select:

<select ng-model="a" ng-trim="false">
    <option value="{{spaceChar}}">Default</option>
</select>