2016-04-12 122 views
0

我有一個JSON文件,看起來像這樣。ng-repeat使用json數據選擇optgroup

[ 
    {"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"} 
] 

我設法創建了一個包含上述所有選項的選擇菜單。

<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> 

我想在下面的選擇中包含類別作爲optgroups。

<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> 
+0

的可能的複製[如何選擇與角度濾波器組數據?](http://stackoverflow.com/questions/14800862/how-can-i-group-data-帶角度過濾器) – Michelangelo

回答

4

試試這個。

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>

+0

這看起來不錯,但我需要的選項的值是在JSON數據中的ID –

+0

我更新了我的答案。 –

+0

非常感謝 –