将ng-options与嵌套数组

时间:2016-02-03 09:42:20

标签: javascript angularjs ng-options

我从服务器上获取了一些数据。数据结构是:

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

我正在尝试使用ng-options显示每个扇区subSectors。因此,当一些人使用下拉列表时,他们将看到所有子部门。

我试过这个,但似乎无法发挥作用:

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

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

有什么建议吗?

4 个答案:

答案 0 :(得分:2)

我创建了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"]
     }];
});

答案 1 :(得分:1)

我创建了一个plunker: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>

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我尝试使用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>

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

  • SUB1
  • SUB2
  • SUB3