ngOptions two level object display
Asked Answered
J

2

6

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.

Jill answered 20/1, 2014 at 8:35 Comment(2)
Have you tried something?Froehlich
The closest I have gotten so far was: "b.items group by b.name for b in model" However, it is not iterating over the inner object and only dispalys it as CSV.Jill
F
8

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>
Froehlich answered 20/1, 2014 at 9:12 Comment(0)
L
1
<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.

Leathery answered 14/3, 2016 at 21:10 Comment(1)
Please explain your answer, especially since you're adding an answer to a question which has had an accepted answer for over a year.Renner

© 2022 - 2024 — McMap. All rights reserved.