在NG-选项中选择默认值 [英] Select default value at ng-options
问题描述
我有这样的code和信息:
I have this code and information:
$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.
我怎样才能得到ID为X的元素的索引数组中的 $ scope.options
?我很肯定会给我解决,但我不知道该怎么做...
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...
推荐答案
刚刚启动控制器时,设置正确的模型值。您可以轻松地通过使用过滤得到正确的数组值,如果你知道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-选项中选择默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!