JDO JDO - 6 months ago 28
Javascript Question

How to correctly use ng-options?

<select class="form-control" ng-model="ad.selected" ng-options="option.name for option in ad.available track by option.value"></select>


Where is my mistake? Why is this set not selected?

options: [{value:"0",name:"First"},{value:"1",name:"Second"}]


Value from server

ad.selected // 1

Answer

Here is an example of how it works,

<select ng-options="option.value as option.name for option in ad.available"  ng-model="ad.selected"></select>

This generates,

<select>
  <option value="option.value">option.name</option>
  ...
</select>

option.name will be the name and option.value will display the value.

ad.selected will have to be the set as the value that is available in the array. 1 or 0.

Updated the fiddle Here is a JSFiddle