Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Do you have any control of your data object, or does it have to look like that? –  Problematic Sep 10 '13 at 20:09
    
@Problematic I have control. thanks –  Andypandy Sep 10 '13 at 20:10

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer
    
This is a good answer. I created a plunk for it so you can see it in action. plnkr.co/edit/LqeGqg1HdOIkiMQrKn72?p=preview –  jessegavin Sep 10 '13 at 21:42
    
Awesome, thank you. Do you know how to prepopulate the <select>... I tried setting $scope.animalSelection.name = 'great dane' but it didn't work. –  Andypandy Sep 11 '13 at 18:45
    
@jessegavin I can however get it to work if I do $scope.animalSelection = animals[1]. This is not ideal... –  Andypandy Sep 11 '13 at 18:51
    
@Andypandy I would very strongly recommend that you use a library like underscore.js which gives you easy methods for dealing with collections. For example, you could use _.findWhere(animals, { name: "great dane"}) instead of animals[1]. underscorejs.org/#findWhere –  jessegavin Sep 11 '13 at 19:34
    
@jessegavin awesome thakns –  Andypandy Sep 11 '13 at 20:54

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.