Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top