我正在显示如下选择对话框:
<select ng-model="myFormData.theList" ng-options="list.listName for list in myList track by list.listValue">
输出如下内容:
<option value="abc">list name 1</option>
<option value="def">list name 2</option>
<option value="ghi">list name 3</option>
<option value="jkl">list name 4</option>
我知道我可以通过数组INDEX进行默认选择,在我的选择中添加一个ng-init,如下所示:
<select ng-model="myFormData.theList" ng-init="myFormData.theList = myList[1]" ng-options="list.listName for list in myList track by list.listValue">
如何通过 list.listValue 设置默认选择?
答案 0 :(得分:4)
在范围上设置一个取值并返回索引的函数:
scope.getIndexFromValue = function(value) {
for(var i=0; i<scope.list.length; i++) {
if(scope.list[i].listValue === value)
return i;
}
};
然后从ng-init标记中调用它:
<select ng-model="myFormData.theList" ng-init="myFormData.theList = myList[getIndexFromValue('abc')]" ng-options="list.listName for list in myList track by list.listValue">
答案 1 :(得分:2)
除了设置函数之外,另一个选项是将搜索到的值从 ng-init 格式化为具有 track by 使用的相同属性的哈希:
<select
ng-init="myFormData.theList = { listValue: 'ghi'}"
ng-model="myFormData.theList"
ng-options="list.listName for list in myList track by list.listValue">
</select>
请参阅:Plunker sample
答案 2 :(得分:0)
根据Angular文档:&#34; ngModel按引用进行比较,而不是值。绑定到一个对象数组时这很重要。&#34;
我能想到的唯一方法就是遍历你的数组并将myFormData.theList设置为等于控制器初始化时或者通过服务调用获取数据时与控制器中的listValue匹配的实际对象。
答案 3 :(得分:0)
<select ng-model="myFormData.theList"
ng-init="myFormData.theList = myList[1].listValue"
ng-options="list.listValue as list.listName for list in myList">