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 ?

4
  • 2
    Possible duplicate of Recursion with ng-repeat in Angular Commented Dec 11, 2018 at 15:50
  • I remembered I wrote a tree structure a while ago using recursion since angularjs (> 1.x (x=5 or 6?)) supports recursion. You can do something similar use ng-content to include child content. Commented Dec 11, 2018 at 15:52
  • @George noted, I didn't knew that Commented Dec 11, 2018 at 15:55
  • @ABOS I am on the 1.6 Commented Dec 11, 2018 at 16:08

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.