Noitidart
Noitidart

Reputation: 37238

Angular select box with value differ from option text

I created an angular select box like this:

<select ng-model="BC.aOptions_aBadge" ng-options="aOptName for aOptName in {0:'NONE', 1:'Top Left', 2:'Top Right', 3:'Bottom Left', 4:'Bottom Right'}" />

This makes the html be:

<select xmlns="http://www.w3.org/1999/xhtml" ng-model="BC.aOptions_aBadge" ng-options="aOptName for aOptName in {0:'NONE', 1:'Top Left', 2:'Top Right', 3:'Bottom Left', 4:'Bottom Right'}" class="ng-pristine ng-valid ng-touched">
    <option value="string:NONE" label="NONE" selected="selected">NONE</option>
    <option value="string:Top Left" label="Top Left">Top Left</option>
    <option value="string:Top Right" label="Top Right">Top Right</option>
    <option value="string:Bottom Left" label="Bottom Left">Bottom Left</option>
    <option value="string:Bottom Right" label="Bottom Right">Bottom Right</option>
</select>

However I want the value of the option to be the key, so it should be 0, 1, 2, 3, 4. While keeping the strings intact, is this possible?

Upvotes: 1

Views: 726

Answers (2)

Archernar
Archernar

Reputation: 463

Here is an example of the correct syntax. Use the keyword 'as' to mark the value you want.

<select
  ng-model="ref.contactTime.startTime" 
  ng-options="hour.Id as hour.Name for hour in contactHours.hours">
   <option disabled selected value="">Select time</option>
                        </select>

Also you might want to put your 'none' value as the default one which is done (as in the example) by placing a option in the select with a blank value.

Upvotes: 1

PSL
PSL

Reputation: 123739

You could use the object syntax (select as label for (key , value) in object), i.e

  ng-options="key as aOptName for (key, aOptName) in {0:'NONE', 1:'Top Left', 2:'Top Right', 3:'Bottom Left', 4:'Bottom Right'}"

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app>

  <select ng-model="BC.aOptions_aBadge" ng-options="key as aOptName for (key, aOptName) in {0:'NONE', 1:'Top Left', 2:'Top Right', 3:'Bottom Left', 4:'Bottom Right'}"></select>
  {{BC.aOptions_aBadge}}
</div>

Upvotes: 2

Related Questions