ng-options with simple array init

Dragu picture Dragu · Aug 13, 2013 · Viewed 184.3k times · Source

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.

Answer

James Davies picture James Davies · Aug 13, 2013

You actually had it correct in your third attempt.

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

See a working example here: http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=preview

The trick is that AngularJS writes the keys as numbers from 0 to n anyway, and translates back when updating the model.

As a result, the HTML will look incorrect but the model will still be set properly when choosing a value. (i.e. AngularJS will translate '0' back to 'var1')

The solution by Epokk also works, however if you're loading data asynchronously you might find it doesn't always update correctly. Using ngOptions will correctly refresh when the scope changes.