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.
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.
Overview. HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
The AngularJS ng-value directive is used to set the value attribute of an input element, or a select element. It is mainly used on <radio> and <option> elements to set the bound values when these elements are selected. It is supported by <input> and <select> elements.
In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With