Using ng-options with nested arrays

岁酱吖の 提交于 2019-12-06 01:21:36

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

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>

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

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