Home > OS >  Separate values in select containing 2 object
Separate values in select containing 2 object

Time:12-12

My contains 2 different objects, obj1 and obj2.

            <select multiple  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},
]}

What I get when I select values :

enter image description here

What I actually want :

I want the values to be in separated arrays since they are both from different objects so 1 array with ['oui','non'] and the second array with ['instance']. How can I do that ?

Visual of the dropdown ( sorry for the big blue lines I wanted to stay on the point with the datas I made in the question )

enter image description here

CodePudding user response:

You can use ngChange to respond to any changes to the ngModel value and store that in a new property:

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>

  • Related