2
votes

I want to list create a list like this using angularjs:

  • Parent 1
  • Group1
  • Child1
  • Child2
  • Child3
  • Child4
  • Group2
  • Child1
  • Child2

    -

  • Parent 2
  • Group1
  • Child1
  • Child2
  • Group2
  • Child1

I have some data in a format similar to this.

$scope.parents = [{
    name:'Parent 1',
    groups: [{
        name:'Group1',
        children:[{name:'Child1'},{name:'Child2'},{name:'Child3'},{name:'Child4'}]
    },{
        name:'Group2',
        children:[{name:'Child1'},{name:'Child2'}]
    }]
 },{
    name:'Parent 2',
    groups: [{
        name:'Group1',
        children:[{name:'Child1'},{name:'Child2'}]
    },{
        name:'Group2',
        children:[{name:'Child1'}]
    }]
 },
 ...
];

I can't figure out a way to loop through the children array with angular. My HTML currently looks like this.

<ul ng-repeat="parent in parents">
    <li class="bold italic">{{parent.name}}</li>
    <li ng-repeat="group in parent.groups" class="bold">{{group.name}}</li>
</ul>

I currently plan to do something like this and then fix it with css, but I'm curious if there is a proper way to do this with angular without having to put lists within lists.

<ul ng-repeat="parent in parents">
    <li class="bold italic">{{parent.name}}</li>
    <ul ng-repeat="group in parent.groups">
        <li class="bold">{{group.name}}</li>
        <li ng-repeat="child in group.children">{{child.name}}</li>
    </ul>
</ul>
1
That I would rather not put an ul inside an ul since then I would have to modify the css so that the inner ul is styled like the outer ul. If the hierarchy ever grew, I'd also not like to keep placing uls in uls for new levels, or at least to have the option. - Sraaz
I should mention that this ul list is stylized to look more like a list like bootstrap list group. - Sraaz

1 Answers

5
votes

I think you should use ng-repeat-start and ng-repeat-end directives like this:

<ul ng-repeat="parent in parents" class="list-group">
    <li class="list-group-item bold italic">{{parent.name}}</li>
    <li class="list-group-item bold" ng-repeat-start="group in parent.groups">
      {{group.name}}
    </li>
    <li class="list-group-item" ng-repeat="children in group.children">
      {{children.name}}
    </li>
    <li class="hide" ng-repeat-end></li>
</ul>

Plunkr live demo.