在 ng-options 处选择默认值 [英] Select default value at ng-options
问题描述
我有这个代码和信息:
$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>
然而,选项是这样创建的:
However, the options are created like this:
<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?我知道这是可以做到的:
How can I set the selected option to My label 2? I know it can be done:
$scope.selected = $scope.options[1];
但我的问题是该选项是在指令中创建的,当时我不知道 1) $scope.options
有多少个值,也不知道 2) 的索引是什么数据库中选择的选项.我唯一知道的是 id(在对象中).
But my problem is that option is created in a directive, and at that moment I don't know 1) how many values has $scope.options
, nor 2) what is the index of the selected option in database. The only thing I know is the id (which is in the object).
我的指令的 html 是这样的:
The html of my directive is something like this:
<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.
And element.options
has the array with options, and form.model[element.model]
has the id of the option selected.
如何获取数组 $scope.options
中 ID 为 X 的元素的索引?我很确定这会给我解决方案,但我不知道该怎么做...
How can I get the index of the element with ID X in the array $scope.options
? I'm very sure that will give me the solution, but I don't know how to do it...
推荐答案
只需在启动控制器时设置正确的模型值即可.如果您使用 filter 知道 ID,则可以轻松获得正确的数组值:
Just set the correct model value when initiating the controller. You can easily get the correct array value if you know the ID by using a filter:
$scope.selected = $filter('filter')($scope.options, {id: 2})[0];
这篇关于在 ng-options 处选择默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!