我有一个对象,其中键的值是数组:例如:
{
key1 : [item1, item2, item3],
key2 : [item4, item5, item6]
}
我想在选择框中显示所有“项目”并按“键”对它们进行分组
我怎样才能用 ng-options 做到这一点?我阅读了文档,但似乎无法弄清楚如何做到这一点。
我有一个对象,其中键的值是数组:例如:
{
key1 : [item1, item2, item3],
key2 : [item4, item5, item6]
}
我想在选择框中显示所有“项目”并按“键”对它们进行分组
我怎样才能用 ng-options 做到这一点?我阅读了文档,但似乎无法弄清楚如何做到这一点。
假设item1
,item2
等是对象:
app.controller('MainCtrl', function($scope) {
$scope.rawItems = {
key1 : [{name: 'item1'}, {name: 'item2'}, {name: 'item3'}],
key2 : [{name: 'item4'}, {name: 'item5'}, {name: 'item6'}]
};
});
<select
ng-model="selectedItem"
class="form-control"
>
<option value=""></option>
<optgroup ng-repeat="(groupName, items) in rawItems" label="{{groupName}}">
<option ng-repeat="item in items" value="{{item.name}}" ng-bind="item.name"></option>
</optgroup>
</select>
您首先需要在控制器中转换您的数组。
app.controller('MainCtrl', function($scope) {
var rawItems = {
key1 : [{name: 'item1'}, {name: 'item2'}, {name: 'item3'}],
key2 : [{name: 'item4'}, {name: 'item5'}, {name: 'item6'}]
};
$scope.groupedItems = [];
var option;
angular.forEach(rawItems, function(items, key){
option = {};
angular.forEach(items, function(item){
item.group = key;
$scope.groupedItems.push(item);
});
});
});
<select
ng-model="selectedGroupedOption"
ng-options="value.name as value.name group by value.group for value in groupedItems"
>
<option>--</option>
</select>