【问题标题】:Using ng-options with nested arrays将 ng-options 与嵌套数组一起使用
【发布时间】:2017-09-28 01:17:46
【问题描述】:

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

[{"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 是从服务器返回的数据。

有什么建议吗?

【问题讨论】:

  • 什么不起作用?控制台错误?选择中没有选项?
  • @JohannesJander 没有选项。选择仍然为空
  • 什么是mySectors?难道你想写mySectors[0].subsectors
  • @JohannesJander mySectors 是来自服务器的数据。它包含问题中数据结构中所示的对象。然后这些对象包含一个嵌套的 subSectors 数组。这就是我想要的,嵌套的 subSectors 数组。
  • 那么,如果你不想聚合多个扇区的子扇区,那么你需要使用mySectors[0].subsectors——这只是一个简单的map操作

标签: javascript angularjs ng-options


【解决方案1】:

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

【讨论】:

  • 做得非常好。很简单!不知道为什么我想不出来。好伙伴!
  • 谢谢老兄。请求请接受答案,如果它适用于您的情况
【解决方案2】:

我已经创建了一个 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>

【讨论】:

  • 非常感谢。不错的技术,我应该考虑在将数据发送到视图之前在控制器中填充数据。学到了一些新东西。队友的欢呼声。 +1
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    我试图做同样的事情,并尝试使用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

    【讨论】: