AngularJS - value attribute for select

Paul picture Paul · Dec 10, 2012 · Viewed 135.6k times · Source

Source JSON data is:

[
  {"name":"Alabama","code":"AL"},
  {"name":"Alaska","code":"AK"},
  {"name":"American Samoa","code":"AS"},
  ...
]

I try

ng-options="i.code as i.name for i in regions"

but am getting:

<option value="?" selected="selected"></option>
<option value="0">Alabama</option>
<option value="1">Alaska</option>
<option value="2">American Samoa</option>

while I am expecting to get:

<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AS">American Samoa</option>

So, how to get value attributes and get rid of "?" item?

By the way, if I set the $scope.regions to a static JSON instead of AJAX request's result, the empty item disappears.

Answer

Mark Rajcok picture Mark Rajcok · Dec 10, 2012

What you first tried should work, but the HTML is not what we would expect. I added an option to handle the initial "no item selected" case:

<select ng-options="region.code as region.name for region in regions" ng-model="region">
   <option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}

The above generates this HTML:

<select ng-options="..." ng-model="region" class="...">
   <option style="display:none" value class>select a region</option>
   <option value="0">Alabama</option>
   <option value="1">Alaska</option>
   <option value="2">American Samoa</option>
</select>

Fiddle

Even though Angular uses numeric integers for the value, the model (i.e., $scope.region) will be set to AL, AK, or AS, as desired. (The numeric value is used by Angular to lookup the correct array entry when an option is selected from the list.)

This may be confusing when first learning how Angular implements its "select" directive.