Trying to pre-select multiple values in my selectfield.
My HTML
<select multiple
data-ng-options="e.id for e in myElements"
data-ng-model="mySelect">
</select>
Put data in the select box (works fine)
var elements = [
{ "id": "AAA" },
{ "id": "BBB" },
{ "id": "CCC" },
{ "id": "DDD" },
{ "id": "EEE" },
{ "id": "FFF" },
{ "id": "GGG" }
]
$scope.myElements = elements;
This does NOT work
var preselected = [
{ "id": "BBB" },
{ "id": "DDD" },
{ "id": "FFF" }
]
$scope.mySelect = preselected;
This does NOT work
var preselected = [ "BBB", "DDD", "FFF" ]
$scope.mySelect = preselected;
Anyone got any ideas?
You have two options:
1- Use as
and track by
if you want objects as selected values ( PLUNKER )
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- Only Use as
syntax if you want strings or numbers as selected values ( PLUNKER )
ng-options="e.id as e.name for e in elements"
e.id
is the value of selected option e.name
is the displayed value In your case: 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"
];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.