javascriptangularjsangularjs-ng-repeatangularjs-select2angularjs-ng-change

Using <select> with nested objects in Angular


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.


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.