1

I have an HTML template to display according to a config the return of a JSON configuration

JSON config :

[
  {
    label: 'Type of contact',
    children: [
      {
        label: 'Type of prospect',
        children: [
          {
            label: 'Seller'
          },
          {
            label: 'Buyer'
          }
        ]
      }
    ]
  }
]

To display it I did :

<div ng-repeat="item in $ctrl.filtersConfig">
  <span>{{ item.label }}</span>

  <div ng-repeat="itemChildren in item.children">
    <ul>{{ itemChildren.label }}
      <div ng-repeat="itemChildrenOfChildren in itemChildren.children">
        <li>{{ itemChildrenOfChildren.label }}</li>
      </div>
    </ul>
  </div>

it works but the problem is that I can have several levels of depth with children, if I ever have 10 depth levels withchildren I will have to do 10 ng-repeat

Do you have ideas of how to handle this with more dynamic ways ?

Mouad Ennaciri
  • 1,217
  • 3
  • 15
  • 28

1 Answers1

1

You could create a component to display a child and its children. For each child, the component can use itself to display the child and its children. If there are several nested layers of children performance will quickly become an issue, but you could limit devise a way to limit the levels displayed. Here's an idea that will handle it with a single ng-repeat in your view no matter how many levels of children there are:

Use this at the top level:

<ul>
    <li>
        {{ topLevelObject.label }}
        <ul>
            <li ng-repeat="child in topLevelObject.children">
                <child-display display-object="child"></child-display>
            </li>
        </ul>
    </li>
</ul>

childDisplay.js

angular.module('app') // assumes an app has already been registered
  .component('childDisplay', {
    bindings: {
      displayObject: '<'
    },
    templateUrl: 'childDisplay.html'
  });

childDisplay.html

{{ $ctrl.displayObject.label }}
<ul ng-if="$ctrl.displayObject.children && $ctrl.displayObject.children.length > 0">
  <li ng-repeat="child in $ctrl.displayObject.children">
    <child-display display-object="child"></child-display>
  </li>
</ul>
Lex
  • 6,758
  • 2
  • 27
  • 42