简体   繁体   中英

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.

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",
    ...
};

以下文章讨论了可以使用ngOptions的多种方式(到目前为止,我见过的最清晰,最彻底的解释): http : //www.undefinednull.com/2014/08/11/a-brief-walk通过angularjs中的ng-options /

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM