在ng-options中选择默认值

Select default value at ng-options

本文关键字:默认值 选择 ng-options      更新时间:2023-09-26

我有这个代码和信息:

$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的元素的索引?我确信这会给我答案,但是我不知道怎么做。

初始化控制器时只需设置正确的模型值。如果您知道ID,可以通过使用过滤器轻松获得正确的数组值:

$scope.selected = $filter('filter')($scope.options, {id: 2})[0];

您的代码的问题,因为我看到它是'选择'值出来的数据库是所选对象的ID,而不是对象本身。这是可以的,但是由于这个差异,你不能简单地设置

$scope.selected = 2 //assuming 2 is the value coming from your database

,因为值'2'不存在于您的选项数组中。ID为2的对象。

如果你总能保证选项数组中的选项是从1-n开始的,并且是按这个顺序排列的,你可以通过简单地使用下面的命令来实现:

$scope.options = [
    { id: 1, label: "My label" },
    { id: 2, label: "My label 2" }
];
var selectedIdFromDatabase = 2;
$scope.selected = $scope.options[selectedIdFromDatabase-1];

如果你不能保证这一点(即使你现在可以,在你的代码中做这个假设可能不是一个好主意),你需要遍历对象数组,你必须从数据库中识别一个ID为selectedId的对象。

这个问题的答案有一篇关于你需要做的数据处理类型的很好的文章,还有很多关于javascript对象的一般信息。