Dayrona Dayrona - 4 months ago 24
AngularJS Question

General way to display any TreeView with AngularJS

I'm working on a project which partially consists of displaying a treeview of documents.

I recently ran into a problem and I don't know how to resolve it so I came here to ask for help.

The issue is I have an array which contains all the data I need. There are docs in folders and/or folders in folders, etc... I know how to render the 'children' of each folder but the problem is I don't know how to do it generally.
I've coded a simple JSFiddle to better illustrate the problem : http://jsfiddle.net/k3nj6pco/

You can see that showing children 1.1 and 1.2 is easy. But I can't figure out how to display child 1.1.1 without making a third

ng-repeat
loop. And I would like to generalize to n depth-level.

Does anyone know how I can resolve this issue ? Thank you very much for your time !

Answer

I would solve this with a recursive directive.

take a look at recursive directives

The gist of it is:

<div ng-controller="IndexCtrl">
  <collection collection='locations'></collection>
</div>

app.directive('collection', function () {
  return {
      restrict: "E",
      replace: true,
      scope: {
          collection: '='
      },
      template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
  }
})

and then:

<member ng-repeat='member in collection' member='member'></member>

app.directive('member', function ($compile) {
  return {
      restrict: "E",
      replace: true,
      scope: {
          member: '='
      },
      template: "<li></li>",
      link: function (scope, element, attrs) {
          if (angular.isArray(scope.member.children)) {
              element.append("<collection collection='member.children'></collection>");
              $compile(element.contents())(scope)
          }
      }
  }
})

so you are compiling the collection directive inside your member directive if there are still children.

kind regards

Comments