-1

I have a data source that looks like this:

var categories = 
[{
{"name":"First Category","subcats":[
{"name":"Sub Category 1"},
{"name":"Sub Category 2"},
{"name":"Sub Category 3"}]
},{
{"name":"Second Category","subcats":[
{"name":"Sub Category 1"},
{"name":"Sub Category 2"},
{"name":"Sub Category 3"}]
}]

I couldn't figure out how to use ng-options to show sub categories grouped by main category. Result should look like this:

<select>
   <optgroup>First Category
      <option>Sub Category 1</option>
      <option>Sub Category 2</option>
      <option>Sub Category 3</option>
   </optgroup>
   <optgroup>Second Category
      <option>Sub Category 1</option>
      <option>Sub Category 2</option>
      <option>Sub Category 3</option>
   </optgroup>
</select>
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Mamo YZ
  • 61
  • 1
  • 8

2 Answers2

1

1) Fix your categories array;

2) Flatten it to use with ngOptions and group by.

Example:

angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
    var categories  = 
    [
        {
            "name": "First Category",
            "subcats": [
                {"name": "Sub Category 1"},
                {"name": "Sub Category 2"},
                {"name": "Sub Category 3"}
            ]
        },
        {
            "name": "Second Category",
            "subcats": [
                {"name": "Sub Category 1"},
                {"name": "Sub Category 2"},
                {"name": "Sub Category 3"},
               {"name": "Sub Category 4"}
            ]
        }
    ];
    
    $scope.options = [];
    
    angular.forEach(categories, function (category){
     angular.forEach(category.subcats, function (subCat){
       subCat.categoryName = category.name;
       $scope.options.push(subCat);
      });
    });
  
});
<script src="https://code.angularjs.org/1.6.2/angular.js" ></script>
<html ng-app="plunker">
  <body ng-controller="MainCtrl">
  
     <select ng-model="test.model" 
        ng-options="option.name group by option.categoryName for option in options">
    </select>
    
  </body>
</html>
Stanislav Kvitash
  • 4,614
  • 18
  • 29
  • Here is another answer with enable/disable individual items: https://stackoverflow.com/questions/18615624/angularjs-ng-options-with-group/37035297#37035297 – Shafqat Nov 29 '17 at 20:12
0
this.categories =
  [
    {
      "name": "First Category",
      "subcats": [
        { "name": "Sub Category 1" },
        { "name": "Sub Category 2" },
        { "name": "Sub Category 3" }]
    },
    {
      "name": "Second Category",
      "subcats": [
        { "name": "Sub Category 4" },
        { "name": "Sub Category 5" },
        { "name": "Sub Category 6" }]
    }
  ];

and in template:

<select>
  <optgroup *ngFor="let category of categories;" label="{{category.name}}">
    <option *ngFor="let sub of category.subcats;">{{sub.name}}</option>
  </optgroup>

rajeev
  • 64
  • 5