Key-value pairs in ng options

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

Is it possible to use such an array?

{ "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 am reading docs , but I cannot figure out how to achieve this.

+57
javascript angularjs select ng-options
Feb 12 '14 at 17:00
source share
3 answers

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 the controller:

 $scope.data = { "key1": "val1", "key2": "val2", "key3": "val3", ... }; 
+135
Feb 12 '14 at 17:04
source share

The following article discusses many ways to use ngOptions (the clearest, most detailed explanation I've ever seen): http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of- the-ng-options-in-angularjs /

+18
02 Oct '14 at 12:43 on
source share

Chen-Tsu Lin provides an answer to this question in both ways. Just want to add some more lines -

Since the ng-repeat directive repeats a block of HTML code for each element in the array, it can be used to create parameters in the drop-down list, but the ng-options directive was made specifically to populate the drop-down list with options and has at least one important advantage:

Dropdowns made using ng-options allow the selected value to be an object, and dropdowns made from ng-repeat should be a string.

Adding an example for the link:

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 full help, go to http://www.w3schools.com/angular/angular_select.asp

+2
Dec 09 '16 at 6:41
source share



All Articles