[angularjs] ng-options with simple array init

I'm a little bit confused with Angular and ng-options.

I have a simple array and I want to init a select with it. But, I want that options value = label.

script.js

$scope.options = ['var1', 'var2', 'var3'];

html

<select ng-model="myselect" ng-options="o for o in options"></select>

What I get:

<option value="0">var1</option>
<option value="1">var2</option>
<option value="2">var3</option>

What I want:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

So I tried:

<select ng-model="myselect2" ng-init=0 ng-options="options[k] as v for (k,v) in options"></select>

<select ng-model="myselect3" ng-init=0 ng-options="b as b for b in options"></select>

(But it didn’t work.)

Edit:

My form is submitted externally, which is why I need 'var1' as the value instead of 0.

This question is related to angularjs ng-grid ng-options

The answer is


you could use something like

<select ng-model="myselect">
    <option ng-repeat="o in options" ng-selected="{{o==myselect}}" value="{{o}}">
        {{o}}
    </option>
</select>

using ng-selected you preselect the option in case myselect was prefilled.

I prefer this method over ng-options anyway, as ng-options only works with arrays. ng-repeat also works with json-like objects.


You can use ng-repeat with option like this:

<form>
    <select ng-model="yourSelect" 
        ng-options="option as option for option in ['var1', 'var2', 'var3']"
        ng-init="yourSelect='var1'"></select>
    <input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>

When you submit your form you can get value of input hidden.


DEMO

ng-selected ng-repeat


<select ng-model="option" ng-options="o for o in options">

$scope.option will be equal to 'var1' after change, even you see value="0" in generated html

plunker


If you setup your select like the following:

<select ng-model="myselect" ng-options="b for b in options track by b"></select>

you will get:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

working fiddle: http://jsfiddle.net/x8kCZ/15/