Search code examples
angularjsangularjs-ng-options

AngularJS Select with ng-options on array of objects


My Data looks as below:

  {
    "count": 0,
    "QHPIssuerNames": [
        "NOV BCBS",
        "mark issuer",
        "Release 3 issuer",
        "Los angles issuer"
     ],
    "QDPIssuerNames": [
        New One",
        "jan issuer",
        "Manage Issuer",
        "test enrollment",
        "testing issuer p"
    ]
}

And I want to add a select to my html loading the data from the array.

<select 
    name="issuer" 
    id="issuer"
    ng-init="vm.selectedData = vm.inputData.issuer[0]" 
    class="form-control" 
    ng-model="vm.inputData.issuer"
    ng-options="label group by group for value in vm.inputData.issuer"></select>

Here is the screenshot of how my dropdown should look like

jsfiddle


Solution

  • My solution involves transforming the object of arrays into and array of objects, I tried creating a solution with the original object, but the problem is that I am not able to create multilevel select using the object. It requires the object to be split into individual elements for me to get the desired result, basically I loop through the original array and delete the first entry which is count:0, since its not needed in the iteration process, then assign the values to the final array.

    var app = angular.module('myApp', []);
    
    app.controller('MyController', function MyController($scope) {
      vm = this;
      vm.inputData = {
        "count": 0,
        "QHPIssuerNames": [
          "NOV BCBS",
          "mark issuer",
          "Release 3 issuer",
          "Los angles issuer"
        ],
        "QDPIssuerNames": [
          "New One",
          "jan issuer",
          "Manage Issuer",
          "test enrollment",
          "testing issuer p"
        ]
      };
      vm.newArray = vm.inputData;
      delete vm.newArray.count;
      vm.finalArray = [];
      for (var k in vm.newArray) {
        for (var j of vm.newArray[k]) {
          vm.finalArray.push({
            key: k,
            value: j
          })
        }
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-controller='MyController as vm' ng-app="myApp">
      <select name="issuer" id="issuer" class="form-control" ng-init="vm.selectedData = vm.finalArray[0]" ng-model="vm.selectedData" ng-options="x.value group by x.key for x in vm.finalArray"></select>
    </div>