尝试在我的选择字段中预先选择多个值。
我的HTML
<select multiple
data-ng-options="e.id for e in myElements"
data-ng-model="mySelect">
</select>
将数据放入选择框(工作正常)
var elements = [
{ "id": "AAA" },
{ "id": "BBB" },
{ "id": "CCC" },
{ "id": "DDD" },
{ "id": "EEE" },
{ "id": "FFF" },
{ "id": "GGG" }
]
$scope.myElements = elements;
这不起作用
var preselected = [
{ "id": "BBB" },
{ "id": "DDD" },
{ "id": "FFF" }
]
$scope.mySelect = preselected;
这不起作用
var preselected = [ "BBB", "DDD", "FFF" ]
$scope.mySelect = preselected;
有人有任何想法吗?
答案 0 :(得分:3)
您有两种选择:
1- 如果您希望将对象作为选定值(PLUNKER)
,请使用as
和track by
ng-options="e as e.id for e in vm.elements track by e.id"
HTML 的
<select multiple
ng-options="e as e.id for e in vm.elements track by e.id"
ng-model="vm.selecetedValues">
</select>
CONTROLLER
function MainCtrl() {
var vm = this;
vm.elements = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];
vm.selectedValues = [
{ "id": "AAA" },
{ "id": "CCC" }
];
}
2- 如果您希望字符串或数字作为选定值,则仅使用as
语法(PLUNKER)
ng-options="e.id as e.name for e in elements"
e.id
是所选选项的值 e.name
是显示的值 在您的情况下:ng-options="e.id as e.id for e in elements"
HTML 的
<select multiple
ng-options="e.id as e.id for e in vm.elements"
ng-model="vm.selecetedValues">
</select>
CONTROLLER
function MainCtrl() {
var vm = this;
vm.elements = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];
vm.selectedValues= [
"BBB",
"DDD"
];
}