key-value pairs in ng-options

I need to use an associative array as data source for my select options using AngularJS.

Is it possible to use an array like this?

{
"key1": "val1",
"key2": "val2",
"key3": "val3",
...
}

and get something like this:

<select>
<option value="key1">val1</option>
<option value="key2">val2</option>
<option value="key3">val3</option>
...
</select>

I read docs, but I can't understand how to achieve this.

97422 次浏览

use ng-option:

<select ng-model="blah" ng-options="key as value for (key , value) in data"></select>

or use ng-repeat:

<select>
<option ng-repeat="(key, value) in data" value="\{\{key}}">\{\{value}}</option>
</select>

data in controller:

$scope.data = {
"key1": "val1",
"key2": "val2",
"key3": "val3",
...
};

The following article discusses the variety of ways that you can use ngOptions (by far the clearest, most thorough explanation I've ever seen): http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/

Answer by Chen-Tsu Lin actually gives both ways of accessing objects. Just want to add few more lines -

Because the ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list, but the ng-options directive was made especially for filling a dropdown list with options and has at least one important advantage:

Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.

Adding an example for the reference:

ng-repeat : http://www.w3schools.com/angular/tryit.asp?filename=try_ng_select_repeat_selected

ng-options: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_select_object

For complete reference, head onto http://www.w3schools.com/angular/angular_select.asp