这似乎困扰着很多人(包括我)。
当ng-options在AngularJS中使用指令填充<select>标签的选项时,我无法弄清楚如何为选项设置值。对此的文档确实不清楚- 至少对于像我这样的简单人而言。
ng-options
<select>
我可以像这样轻松设置选项的文本:
ng-options="select p.text for p in resultOptions"
resultOptions例如,何时:
resultOptions
[ { "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" } ]
设置选项值应该是(可能是)最简单的事情,但是到目前为止,我还是不明白。
ngOptions(可选) – { comprehension_expression=} –以下形式之一:
comprehension_expression=
对于数组数据源 : 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 对于对象数据源: 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
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
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的更新,现在可以为带有表达式value的selectelement 属性设置实际值track by。
value
select
track by
<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>元素中显示的文本(标签)。
就像,我们需要person.id代码,但是我们不想向id用户显示。我们想显示它的名字。同样,我们person.name对代码不感兴趣。有as关键字标记东西。这样就变成了这样:
person.id
id
person.name
as
person.id as person.name for person in people
或者,代替person.id我们可能需要person实例/引用本身。见下文:
person
person as person.name for person in people
对于JavaScript对象,也适用相同的方法。只要记住对象中的项目是用(key, value)成对解构的。
(key, value)