Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
Skywalker Avatar asked Dec 14 '25 00:12

Skywalker


1 Answers

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"]
     }];
});
like image 55
Shashank Avatar answered Dec 16 '25 12:12

Shashank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!