在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>
但是,这些选项是这样创建的:
<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对象的一般信息。
相关文章:
- jquery日期选择器年份范围默认值
- Selectize选择默认值
- 如果用户未选中复选框或选择按钮,如何为复选框或单选按钮设置一些默认值
- ng-model 绑定到选择标签生成的空默认值
- AngularJS-选择,设置编辑/新建的默认值
- HTML选择:将默认值设置为给定值,而不是从选项列表中选择
- 使用复杂对象上的删除为选择框手动设置默认值
- 修改jQuery脚本,让我选择页面入口的选择列表的默认值
- html 选择中的默认值
- 在 HTML 中选择中使用 Vue.js 和 Minimalect 显示默认值
- 挖空 + 选择2 -- 设置默认值
- 使默认值成为先前选择的值 (JSTL)
- Ajax 选择立即更改默认值
- 如何设置 HTML 选择的默认值
- AngularJS选择带有ng-model和ng-repeat的默认值,而不是ng-option
- AngularJS - 选择 - 服务器调用的默认值
- 当父选择为空时,子选择列表中的默认值将消失
- 在多选下拉列表中选择默认值
- 为什么不将 jQuery UI 日期选择器的默认值设置为匿名函数
- Shopify |为产品下拉框设置默认值'/ '选择尺寸'