Search code examples
javascripthtmlangularjsng-options

ngOptions two level object display


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.


Solution

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