我想选择数组数据源中所选项目的索引。或者,换句话说,我想要 value
<option>
的属性等于索引值,例如0, 1, 2, ...
:
<select name="networkname" class="form-control" id="networkname" ng-model="selectedNetwork" ng-options="network.id as network.name for network in networksList" ng-change="get($index)"</select>
那么我的输出 HTML 是:
<option value="object:57" label="A5 (2 cores, 14336 MB)" selected="selected">A5 (2 cores, 14336 MB)</option>
<option value="object:58" label="A6 (4 cores, 28672 MB)">A6 (4 cores, 28672 MB)</option>
但我想要 value
成为:
<option value="0" label="A5 (2 cores, 14336 MB)" selected="selected">A5 (2 cores, 14336 MB)</option>
<option value="1" label="A6 (4 cores, 28672 MB)">A6 (4 cores, 28672 MB)</option>
这是源数组:
$scope.networkList = [
{id: "A5", name: "A5 (2 cores, 14336 MB)", cpus: 2, disk: null, memory: "14.0 GB"},
{id: "A6", name: "A6 (4 cores, 28672 MB)", cpus: 4, disk: null, memory: "28.0 GB"}
];
最佳答案
据我所知,Angular 有两种方法(1.2.x 和 1.3.x)可以做到这一点 - 没有一种方法是完美的:
- 将源数组视为对象源
- 使用
ng-repeat
生成选项
因此,假设有以下虚拟机:
$scope.items = [{id: "a", n: "b"}, ...]
替代方案#1
<select ng-model="selectedIndexStr"
ng-options="idx as item.n for (idx, item) in items">
缺点:
-
selectedIndexStr
将是一个字符串,而不是整数,因为idx
被视为对象的属性键,而不是数组的索引。这可能对您有用,也可能不起作用,但是,为了说明这一点,如果您想设置ng-model
对于默认值,它必须是$scope.selectedIndexStr = "0"
(注意""
) - 顺序将基于索引值的字符串比较。因此,如果您有超过 10 件商品,则顺序为:
"0", "1", "10", "11", "2", "3", ...
替代方案#2
<select ng-model="selectedIndex">
<option ng-repeat="item in items" value="{{$index}}"
ng-selected="selectedIndex === $index">{{item.n}}</option>
</select>
这里的缺点是它更冗长,因为它不使用 ng-options
这是一个plunker显示替代方案
题外话:
但在典型情况下,人们会想要实际选定的对象,或者有时 - 该对象的属性。如果您依赖于存储对象的数组的索引,那么也许您应该重新评估您的 ViewModel 设计。
因此,以下内容对我来说最有意义:
<select ng-model="selectedItem" ng-options="item as item.n for item in items">
或者,
<select ng-model="selectedItemId" ng-options="item.id as item.n for item in items">
关于javascript - <select> 选择等于源数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337894/