AngularJS在对象数组上选择ng-options

时间:2017-10-21 02:51:00

标签: angularjs angularjs-ng-options

我的数据如下所示:

  {
    "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"
    ]
}

我想在我的html中添加一个select来加载数组中的数据。

<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

1 个答案:

答案 0 :(得分:1)

我的解决方案涉及将object of arrays转换为array of objects,我尝试使用原始对象创建解决方案,但问题是我无法使用该对象创建多级选择。它要求将对象拆分为单独的元素以便我获得所需的结果,基本上我遍历原始数组并删除第一个条目count:0,因为它在迭代过程中不需要,然后分配值到最终数组。

&#13;
&#13;
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
      })
    }
  }
});
&#13;
<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>
&#13;
&#13;
&#13;