My 包含 2 個不同的物件,obj1 和 obj2。
<select multiple class="full-width" style="min-height: 200px" ng-model="vm.obj1" >
<optgroup label="First obj">
<option ng-repeat="item in vm.obj1" >{{item.valeur}}</option>
</optgroup>
<optgroup label="Second obj">
<option ng-repeat="item in vm.obj2">{{item.libelle}}</option>
</optgroup>
</select>
obj1 = {[
0: {valeur: non},
1: {valeur: oui}
]}
obj2 = {[
0: {libelle: instance},
]}
當我選擇值時我得到了什么:

我真正想要的是:
我希望這些值位于單獨的陣列中,因為它們都來自不同的物件,因此第一個陣列['oui','non']和第二個陣列['instance']。我怎樣才能做到這一點 ?
下拉選單的視覺效果(對不起,我想保留我在問題中制作的資料的重點)

uj5u.com熱心網友回復:
您可以使用ngChange來回應對ngModel值的任何更改并將其存盤在新屬性中:
function ctrl($scope) {
$scope.options = [{
name: "A",
options: ["A1", "A2"]
},
{
name: "B",
options: ["B1", "B2"]
},
];
$scope.parseSelection = function() {
const selected = {};
// Loop over the selected options and check from which group they came
$scope.rawSelected.forEach((value) => {
$scope.options.forEach(({ name, options }) => {
if (options.includes(value)) {
// The option comes from the current group
if (!selected[name]) {
selected[name] = [];
}
selected[name].push(value);
}
});
});
$scope.selected = selected;
};
}
angular.module("app", [])
.controller("ctrl", ctrl)
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select multiple ng-model="rawSelected" ng-change="parseSelection()">
<optgroup ng-repeat="group in options" label="group.name">
<option ng-repeat="option in group.options">{{option}}</option>
</optgroup>
</select>
{{rawSelected}} - {{selected}}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389064.html
