See ngOptions
ngOptions(optional) – {comprehension_expression=} – in one of the
following forms:
For array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
For object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object
对你来说,应该是
array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];
<select ng-options="obj.value as obj.text for obj in array"></select>
更新
随着AngularJS的更新,现在可以用track by表达式为select element的value属性设置实际值了。
<select ng-options="obj.text for obj in array track by obj.value">
</select>
如何记住这些丑陋的东西
对于那些很难记住这种语法形式的人:我同意这不是最简单或最漂亮的语法。这种语法是Python列表推导式的扩展版本,知道这一点有助于我很容易地记住语法。大概是这样的:
Python代码:
my_list = [x**2 for x in [1, 2, 3, 4, 5]]
> [1, 4, 9, 16, 25]
# Let people to be a list of person instances
my_list2 = [person.name for person in people]
> my_list2 = ['Alice', 'Bob']
这实际上与上面列出的第一个语法相同。但是,在<select>中,我们通常需要区分代码中的实际值和<select>元素中显示的文本(标签)。
比如,我们需要人手。Id,但我们不想把Id显示给用户;我们想要显示它的名字。同样,我们对代码中的person.name不感兴趣。这里有as关键字来标记东西。所以它变成了这样:
person.id as person.name for person in people
或者,代替person。Id我们可能需要person实例/引用本身。见下文:
person as person.name for person in people
对于JavaScript对象,同样的方法也适用。只需要记住,对象中的项是用(key, value)对解构的。