Angularjs ngOption with array Angularjs ngOption with array angularjs angularjs

Angularjs ngOption with array


With AngularJS, you don't need to worry about what the value of the option is. All the selects I've seen with ng-options have values of 0 through whatever. If you're just looking for a dropdown with the two options, it can be as simple as

<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>

See http://jsfiddle.net/EyBVN/1/


This is is a default behavior of ng-options in Angular. If you do not specify a key name, angular will automatically choose to use the index rather than a key. The code that does that can be seen on line 405 in /src/ng/directives/select.js on Angular's Github repository.

It can't even be forced by "value as value for (index, value) in values".

But as dnc253 just beat me to the punch with his answer (it showed up while I was typing)... you don't have to worry about it, Angular does it all for you automatically.


I did find a way to place specific data in the value of the options for a select. You have to add an ng-repeat attribute to the option tag inside the select tag:

<select id="{{question.id}}" name="{{question.id}}"     class="{{question.inputclass}}" ng-required="question.required"     title="{{question.title}}">  <option value=""></option>  <optgroup ng-repeat="group in question.data" label="{{group.group}}">    <option ng-repeat="item in group.data" value="{{item.value}}"         ng-selected="{{item.value == question.defaultValue}}">          {{item.description}}    </option>  </optgroup></select>

As a bonus, I left the option group tags in place to serve as an example for everyone.

The question.data JSON is:

[  {"group":"Canada","data":[{"value":"Ontario","description":"Toronto"},                            {"value":"Quebec","description":"Quebec City"},                            {"value":"Manitoba","description":"Winnipeg"}                           ]  },  {"group":"Mexico","data":[{"value":"Jalisco","description":"Guadalajara"},                            {"value":"Nayarit","description":"Tepic"}                           ]  },  {"group":"United States of America","data":[                            {"value":"Alabama","description":"Montgomery"},                            {"value":"Georgia","description":"Atlanta"},                            {"value":"Mississippi","description":"Jackson"},                            {"value":"Louisiana","description":"Baton Rouge"},                            {"value":"Texas","description":"Ausint"}                           ]  }]