将 ng-options 与嵌套数组一起使用

Using ng-options with nested arrays

我正在从我的服务器取回一些数据。数据结构为:

[{"sectorName1": "nameHere",
  "subSectors": ["sub1", "sub2", "sub3"]
 },
 {"sectorName2": "nameHere",
  "subSectors": ["sub1", "sub2", "sub3"]
 }]

我正在尝试使用 ng-options 显示每个扇区子扇区。因此,当一些人使用下拉菜单时,他们会看到所有的子行业。

我已经试过了,但似乎不起作用:

<select id="selectSubSector" class="form-control" name="subSector" ng-model="item" ng-options="sec for sec in mySectors.subSectors ">
</select>

其中 mySectors 是从服务器返回的数据。

有什么建议吗?

mySectors 是一个数组。所以没有mySectors.subSectors。您必须为 mySectors 指定索引。例如 mySectors[i].subsectors

我已经创建了一个插件:https://plnkr.co/edit/3QkxdT6P8upwhwttUSDc?p=preview

js代码:

  $scope.mySectors = [{
    "sectorName1": "nameHere",
    "subSectors": ["sub1", "sub2", "sub3"]
  }, {
    "sectorName2": "nameHere",
    "subSectors": ["sub1", "sub2", "sub3"]
  }];

  $scope.subSectors = new Array();
  for (var i = 0; i < $scope.mySectors.length; i++) {
       for(var j=0; j< $scope.mySectors[i].subSectors.length; j++){

    $scope.subSectors.push($scope.mySectors[i].subSectors[j]);
       }
  }

html代码:

<select id="selectSubSector" class="form-control" name="subSector" ng-model="item" ng-options="sec for sec in subSectors"></select>

我创建了一个 jsfiddle,也更新了您的回复数据:

HTML:

<div ng-app="app" ng-controller='TestCtrl'>
    <select ng-model="selectData">
        <option value="">Select</option>
        <optgroup ng-repeat='item in data' label="{{item.sectorName}}">
            <option ng-repeat="option in item.subSectors">{{option}}</option>
        </optgroup>
    </select>
</div>

JS

var app = angular.module('app', []);

app.controller('TestCtrl', function ($scope) {
    $scope.data = [{
        "sectorName": "nameHere1",
        "subSectors": ["sub1", "sub2", "sub3"]
    },
     {
         "sectorName": "nameHere2",
         "subSectors": ["sub1", "sub2", "sub3"]
     }];
});

我试图做同样的事情和一个解决方案,通过使用 ng-if="false"style="display: none"ng-repeat-start/end.

来显示子部分
<div ng-repeat="sector in Sectors">
<select>
    <option ng-repeat-start="subSectors in sector.subSectors" ng-if="false"></option>
    <option ng-repeat-end ng-repeat="subSectorValue in subSectors" value="{{ subSectorValue }}">{{ subSectorValue }}</option>
</select>
</div>

这为我们提供了一个包含以下选项的 select 框。

  • sub1
  • sub2
  • sub3
  • 等等