0

I am having a problem in which I cannot find the answer anywhere on the internet. I am trying to dynamically create a category list in AngularJS where I don´t know on forehand how many levels I need. The values are fetched from a database, with a parentID, and each element may have one or more children.

I have used ng-repeat before to create two-level lists, but I do not know how to add more levels without nesting as many repeats as I need on forehand. I know how to do this in php to generate the data, but that is not what I wish to accomplish.

I might need to use directives or some sort, but I need someone to point me in the right direction.

There is kind of a solution in this plunk: http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview but I think this is a very dirty fix, and I am really searching for a better one.

Thank you for any tips or hints.

Kind regards, Kjetil.

Kjetil Haaheim
  • 240
  • 1
  • 2
  • 10
  • 1
    look at demos in this post http://stackoverflow.com/questions/11854514/is-it-possible-to-make-a-tree-view-with-angular – charlietfl Mar 25 '13 at 13:07
  • That is not a dirty fix. That is probably the right way to do it. Why do you think it is dirty? It uses a concept of recursion which is kind of how you would render a tree component anyway.. – ganaraj Mar 25 '13 at 14:18

1 Answers1

0

You could create a directive that decides how many levels there will be and build/$compile the template in the link function. More info on how to create a directive here.

app.directive('categoryList', function($compile) {
  return {
    link: function(scope, elm, attr) {
      scope.$watch('somethingThatShowYouShouldRebuild', function() {
        // all the log that figures aout how many levels (a recursive function probably)
        // that will build the HTML template with all nested ng-repeat's
        var template = // ...
        elm.html(template);
        $compile(elm)(scope);
      });
    }
  }
});
Caio Cunha
  • 23,326
  • 6
  • 78
  • 74