문제

I'd like to create an html output like this:

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

From an array like this:

 var animals = [{
     name: 'Dogs',
     subcats: ['great dane', 'lab']
 }, {
     name: 'Cats',
     subcats: ['tabby', 'black']
 }, ];

And have the model bound to the to set 2 values, animal.type(dog or cat) and animal.subcategory.

Tried a bunch of stuff... am thinking I'll need to use ng-repeat and hack it through... any help is much appreicated.

도움이 되었습니까?

해결책

Since you can control the model, the documentation has an example here.

Transform your model to look like:

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;

And the select would look like:

<select ng-model="..." ng-options="a.name group by a.subcat for a in animals">

The selection will be the entire animal object with name and subcat properties.

다른 팁

An alternative without needing to flatten your data would be to use nested ng-repeat directives as in this post.

<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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top