我想创建一个这样的 html 输出:
<select>
<option value="" class="">-- Choose category --</option>
<optgroup label="Dogs">
<option value="0">Great Dane</option>
<option value="1">Lab</option>
</optgroup>
<optgroup label="Cats">
<option value="2">Black</option>
<option value="3">Tabby</option>
</optgroup>
</select>
从这样的数组:
var animals = [{
name: 'Dogs',
subcats: ['great dane', 'lab']
}, {
name: 'Cats',
subcats: ['tabby', 'black']
}, ];
并将模型绑定到设置2个值,animal.type(狗或猫)和animal.subcategory。
尝试了一堆东西...我想我需要使用 ng-repeat 并破解它......任何帮助都非常感激。
由于您可以控制模型,因此文档在此处提供了一个示例。
将模型转换为如下所示:
var animals = [
{name: "great dane", subcat: "Dogs"},
{name: "lab", subcat: "Dogs"},
{name: "tabby", subcat: "Cats"},
{name: "black", subcat: "Cats"}
];
// and put it in the $scope
$scope.animals = animals;
选择将如下所示:
<select ng-model="..." ng-options="a.name group by a.subcat for a in animals">
选择将是具有name
和subcat
属性的整个动物对象。
无需扁平化数据的另一种方法是使用嵌套的ng-repeat
指令,如本文所示。
<div ng-repeat="people in People">
<label>{{people.firstName}}</label>
<select>
<option ng-repeat-start="choice in people.Choices" ng-bind="choice.Name"></option>
<option ng-repeat-end ng-repeat="opt in choice.Options" ng-bind="' - ' + opt.Name"></option>
</select>
</div>
http://plnkr.co/edit/2vj4PK?p=preview