$scope.items = [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}];
根据上面的列表,以下是我通常使用的:
<select ng-options="item in items" ng-model="selected"></select>
非常简单,例如,我可以使用 item.xxx
访问该值
但是下面的语法是什么:
<select ng-options="item as item.label for item in items" ng-model="selected"></select>
我完全模糊了,as
和for
关键字的目的是什么?我实在找不到解释这一点的文档,请帮忙。
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
但我删除了 track by
,因为我通过阅读文档了解了这一点。
最佳答案
这是 <select>
的选项列表应引用填充选项。
$scope.items = [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}];
当你写ng-options="item as item.label for item in items"
时,您正在迭代 items
,其中每个项目都分配给 item
通过使用item in items
.
因此,对于第一次迭代,item
的值将是:
{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}
请注意item
在本例中是一个对象。
<option>
不关心您如何为其获取数据,它只关心它需要显示的内容以及在选择它时分配什么值。所以,我们告诉ng-options
使用for
需要 item
作为输入并生成对应的<option>
元素。
现在在选择选项中,假设您希望输入为 id
。但是嘿,谁知道你的 id
是什么意思? ,为了人类可读,您需要显示一些有意义的消息来识别它,即 label
在这种情况下。
因此,您将仅使用它的id
,而不是使用整个对象。使用label
时识别它(下拉列表中显示的文本)。
现在您的代码更改为:
ng-options="item.id as item.label for item in items"
所以最终生成的 HTML 变成这样:
<select>
<option value="1">aLabel</option>
<option value="2">bLabel</option>
</select>
关于javascript - Angularjs ngrepeat和ngoptions, "as" "for"关键字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39409371/