以下是困扰很多人(包括我)的问题。

当在AngularJS中使用ng-options指令来填充<select>标记的选项时,我不知道如何为一个选项设置值。这方面的文档确实不清楚——至少对我这样的傻瓜来说是这样。

我可以像这样轻松地设置一个选项的文本:

ng-options="select p.text for p in resultOptions"

例如,当resultOptions为:

[
    {
        "value": 1,
        "text": "1st"
    },
    {
        "value": 2,
        "text": "2nd"
    }
]

它应该是(可能是)设置选项值最简单的事情,但到目前为止,我只是不明白它。


当前回答

您可以使用ng-options实现选择标记绑定到值和显示成员

在使用此数据源时

countries : [
              {
                 "key": 1,
                 "name": "UAE"
             },
              {
                  "key": 2,
                  "name": "India"
              },
              {
                  "key": 3,
                  "name": "OMAN"
              }
         ]

可以使用下面的代码将选择标记绑定到值和名称

<select name="text" ng-model="name" ng-options="c.key as c.name for c in countries"></select>

效果很好

其他回答

根据我的说法,这是最适合所有场景的:

<select ng-model="mySelection.value">
   <option ng-repeat="r in myList" value="{{r.Id}}" ng-selected="mySelection.value == r.Id">{{r.Name}}
   </option>
</select>

您可以使用您的模型来绑定数据。您将获得对象将包含的值以及基于您的场景的默认选择。

这个问题的正确答案由用户frm提供。Adiputra,因为目前这似乎是显式控制选项元素的value属性的唯一方法。

然而,我只是想强调,“select”在这里不是关键字,而只是表达式的占位符。请参考以下列表,“select”表达式的定义以及ng-options指令中可以使用的其他表达式。

问题中描述的select的用法:

ng-options='select p.text for p  in resultOptions'

本质上是错误的。

根据表达式列表,当在对象数组中给出选项时,似乎可以使用trackexpr来指定值,但它仅用于分组。


来自AngularJS的ng-options文档:

array / object: an expression which evaluates to an array / object to iterate over. value: local variable which will refer to each item in the array or each property value of object during iteration. key: local variable which will refer to a property name in object during iteration. label: The result of this expression will be the label for element. The expression will most likely refer to the value variable (e.g. value.propertyName). select: The result of this expression will be bound to the model of the parent element. If not specified, select expression will default to value. group: The result of this expression will be used to group options using the DOM element. trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).

用一个普通的表单提交发送一个名为my_hero的自定义值给服务器:

JSON:

"heroes": [
  {"id":"iron", "label":"Iron Man Rocks!"},
  {"id":"super", "label":"Superman Rocks!"}
]

HTML:

<select ng-model="hero" ng-options="obj.id as obj.label for obj in heroes"></select>
<input type="hidden" name="my_hero" value="{{hero}}" />

服务器将接收my_hero的值为iron或super。

这类似于@neemzy的回答,但是为value属性指定了单独的数据。

ng-options指令不会为数组的<options>元素设置value属性:

使用限制。值为极限。“limits”中的“limit”表示:

将<option>的标签设置为limit.text 保存限制。Value值到选择的ng-model中

参见Stack Overflow问题AngularJS ng-options不呈现值。

value属性如何获取其值:

当使用数组作为数据源时,它将是数组元素在每次迭代中的索引; 当使用对象作为数据源时,它将是每次迭代中的属性名。

所以在你的例子中,它应该是:

obj = { '1': '1st', '2': '2nd' };

<select ng-options="k as v for (k,v) in obj"></select>