我有这个代码和信息:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
$scope.selected = 2;
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
</select>
但是,选项是这样创建的:
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
<option value="0">My label</option>
<option value="1">My label 2</option>
</select>
如何将所选选项设置为我的标签 2?我知道这是可以做到的:
$scope.selected = $scope.options[1];
但我的问题是选项是在指令中创建的,当时我不知道 1) 有多少个值有 $scope.options
,也不知道 2) 的索引是什么数据库中选定的选项。我唯一知道的是 id(位于对象中)。
我的指令的 html 是这样的:
<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>
其中 element.rule
是:
rule: "role.role for role in element.options"
element.options
包含带有选项的数组,form.model[element.model]
包含所选选项的 ID。
如何获取数组$scope.options
中ID为X的元素的索引?我非常确定这会给我解决方案,但我不知道该怎么做......
最佳答案
只需在启动 Controller 时设置正确的模型值即可。如果您知道 ID,则可以使用 filter 轻松获得正确的数组值。 :
$scope.selected = $filter('filter')($scope.options, {id: 2})[0];
关于javascript - 在 ng-options 中选择默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25222309/