key-value pairs in ng-options

JavascriptAngularjsSelectNg Options

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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/

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaviooohView Question on Stackoverflow
Solution 1 - JavascriptChen-Tsu LinView Answer on Stackoverflow
Solution 2 - JavascriptMarkus HayView Answer on Stackoverflow
Solution 3 - JavascriptJanusz01View Answer on Stackoverflow