具有值的角度选择框与选项文本不同

时间:2015-09-08 21:29:05

标签: angularjs

我创建了一个像这样的角度选择框:

<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'}" />

这使得html成为:

<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>

但是我希望选项的值是键,所以它应该是0,1,2,3,4。在保持字符串完整的同时,这可能吗?

2 个答案:

答案 0 :(得分:2)

您可以使用object syntax select as label for (key , value) in object ),即

  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>

答案 1 :(得分:1)

以下是正确语法的示例。使用关键字&#39;作为&#39;标记你想要的价值。

<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>

你也许想要把你的“没有”通过在选项中放置一个带空白值的选项,将值作为默认值(如示例中所示)。