Search code examples
javascriptangularjsng-options

Using ng-options with nested arrays


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?


Solution

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