0

I have a JSON file which looks like this.

[
  {"id":1,"catid":1,"Cat":"Category 1","label":"Label 1"},
  {"id":2,"catid":1,"Cat":"Category 1","label":"Label 2"},
  {"id":3,"catid":2,"Cat":"Category 2","label":"Label 3"},
  {"id":4,"catid":2,"Cat":"Category 2","label":"Label 4"},
  {"id":5,"catid":2,"Cat":"Category 2","label":"Label 5"},
  {"id":6,"catid":3,"Cat":"Category 3","label":"Label 6"}
]

I have managed to create a select menu which includes all the above.

<select>
   <option ng-repeat="referral in referralList" value="{{referral.id}}">{{referral.label}}</option>
</select>

Which produces this...

<select>
  <option value="1">Label 1</option>
  <option value="2">Label 2</option>
  <option value="3">Label 3</option>
  <option value="4">Label 4</option>
  <option value="5">Label 5</option>
  <option value="6">Label 6</option>
</select>

I want to include the categories as optgroups within the select like below.

<select>
  <optgroup label="Category 1">
    <option value="1">Label 1</option>
    <option value="2">Label 2</option>
  </optgroup>
  <optgroup label="Category 2">
    <option value="3">Label 3</option>
    <option value="4">Label 4</option>
    <option value="5">Label 5</option>
  </optgroup>
  <optgroup label="Category 3">
    <option value="6">Label 6</option>
  </optgroup>
</select>
Matt H
  • 77
  • 1
  • 8
  • Possible duplicate of [How can I group data with an Angular filter?](http://stackoverflow.com/questions/14800862/how-can-i-group-data-with-an-angular-filter) – Michelangelo Apr 12 '16 at 08:41

1 Answers1

4

try like this.

var app = angular.module("app",[]);

app.controller("ctrl" , function($scope){
  
  $scope.data = [
  {"id":1,"catid":1,"Cat":"Category 1","label":"Label 1"},
  {"id":2,"catid":1,"Cat":"Category 1","label":"Label 2"},
  {"id":3,"catid":2,"Cat":"Category 2","label":"Label 3"},
  {"id":4,"catid":2,"Cat":"Category 2","label":"Label 4"},
  {"id":5,"catid":2,"Cat":"Category 2","label":"Label 5"},
  {"id":6,"catid":3,"Cat":"Category 3","label":"Label 6"}
]
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">

        <select ng-model="model" ng-options="d.label group by d.Cat for d in data track by d.id"></select> 
</div>
Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • That looks great but I need the value of the options to be the id in the JSON data – Matt H Apr 12 '16 at 08:42
  • This is extremely helpful. In my case, I wanted a select element where only some of the options were in option groups. I discovered all that was required for this was to remove the "Cat" key and value entirely from the data dictionary. – trubliphone Feb 10 '17 at 13:05
  • This also helped me understand the `group by` option when using ng-repeat. Thank you! – kneeki May 19 '17 at 11:24