Using ng-options with nested arrays

放肆的年华 提交于 2020-01-02 07:43:09

问题


I am getting some data back from my server. The data structure is:

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

I am trying to display each sectors subSectors with ng-options. So when some uses the dropdown they will see all the subsectors.

I have tried this but doesn't seem to work:

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

where mySectors is the data that comes back from the server.

Any suggestions?


回答1:


I have created a jsfiddle, have updated your response data as well:

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:


i have create a plunker:https://plnkr.co/edit/3QkxdT6P8upwhwttUSDc?p=preview

the js code:

  $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]);
       }
  }

the html code:

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



回答3:


mySectors is an array. So there is no mySectors.subSectors. You have to specify index for mySectors. For example mySectors[i].subsectors




回答4:


I was trying to do the same thing and a solution to just display the sub-sections by using ng-if="false" or style="display: none" and 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>

This gives us a select box with the following options.

  • sub1
  • sub2
  • sub3
  • etc


来源:https://stackoverflow.com/questions/35173373/using-ng-options-with-nested-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!