这似乎困扰着很多人(包括我)。
在使用ng-optionsAngularJS 中的指令填充<select>标签的选项时,我无法弄清楚如何设置选项的值。这方面的文档真的不清楚 - 至少对于像我这样的傻瓜来说。
ng-options
<select>
我可以像这样轻松地为选项设置文本:
ng-options="select p.text for p in resultOptions"
resultOptions例如什么时候:
resultOptions
[ { "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" } ]
设置选项值应该是(并且可能是)最简单的事情,但到目前为止我还是不明白。
见 ngOptions ngOptions(optional) ” { 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
见 ngOptions
ngOptions(optional) ” { 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属性设置实际值。select``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)