gpt4 book ai didi

javascript - 如何在 AngularJS 的 ng-options 中设置 value 属性?

转载 作者:IT老高 更新时间:2023-10-28 11:14:20 34 4
gpt4 key购买 nike

这似乎困扰着很多人(包括我)。

使用 ng-options 时AngularJS 中的指令来填写 <select> 的选项标签,我不知道如何设置选项的值。这方面的文档真的不清楚 - 至少对于像我这样的傻瓜来说。

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

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

resultOptions例如:

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

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

最佳答案

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 的更新,现在可以为 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 as person.name for person in people

或者,而不是 person.id我们可能需要 person实例/引用本身。见下文:

person as person.name for person in people

对于 JavaScript 对象,同样的方法也适用。请记住,对象中的项目是用 (key, value) 解构的。对。

关于javascript - 如何在 AngularJS 的 ng-options 中设置 value 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139152/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com