ngOptions two level object display

All we need is an easy explanation of the problem, so here it is.

I have this structure:

model = [
{
  name: 'name1',
  items: [
    {
      name: 'subobj1'
    },
    {
      name: 'subobj2'
    }]
}, 
{
  name: 'name2',
  items: [
    {
      name: 'subobj1'
    },
    {
      name: 'subobj2'
    }]
}, 
    .... 
]

Question is: How do I write ngOptions attrbiute to output this object like this?:

<select>
    <optgroup label="name1">
      <label>subobj1</label>
      <label>subobj2></label>
    </optgroup>
    ....
</group>

Also – ngRepeat is not an option. I have to do this ngOptions alone for plugin being used to work.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

ngOptions doesn’t support multi-dimensional arrays. You must flatten your array first.

Read more in this answer.

I used a filter:

app.filter('flatten' , function(){
  return function(array){
    return array.reduce(function(flatten, group){
      group.items.forEach(function(item){
        flatten.push({ group: group.name , name: item.name})
      })
      return flatten;
    },[]);
  }
})

And the markup:

<select ng-model="select"
        ng-options="item.name 
                    group by item.group 
                    for item in model | flatten"></select>

Method 2

<select>
    <option ng-repeat-start="m in model" ng-bind="m.name"></option>
    <option ng-repeat-end ng-repeat="item in m.items" ng-bind="item.name"></option>
</select>

You might add something like style="font-weight: bold;" on the first option (which is the group label, by the way) and something like style="padding-left: 15px;" on the second option line, which is another repeat for all the first option line.
So basically by doing this you just add 2 levels (without optgroup tag, mind you) to your select.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply