3

I have the following data structure declared in my controller:

$scope.tree = {
    label:"A",
    parent:{
        label:"B",
        parent:{
            label:"C"
        }
    }
};

What i would like to end up with is:

<ul>
  <li>C
    <ul>
      <li>B
        <ul>
          <li>A</li>
        </ul>
      </li>
    </ul>
  </li>
<ul>

I've tried various ways of doing this including external templates, custom directives etc and I just can't seem to get it to work.

Any thoughts?

Randyaa
  • 2,935
  • 4
  • 36
  • 49
  • I think it would simplify things to reverse the tree before adding it to the scope – Explosion Pills Jul 30 '14 at 18:30
  • Do you need that structure specifically? It makes more sense to me if you swap "A" and "C" and rename `parent` to `children`. – Andy Gaskell Jul 30 '14 at 19:03
  • I have drastically simplified the structure and it is coming from an existing service – Randyaa Jul 30 '14 at 19:14
  • So I've successfully reversed the order of the data but I still can't figure out a way to make this happen without modifying the data structure so that at each level you have a list of objects instead of a singleton. If there is a list, the issue can be solved by something like the answer here: http://stackoverflow.com/questions/15661289/how-can-i-make-recursive-templates-in-angularjs-when-using-nested-objects I could modify the data structure again, but I'd like to avoid that if I can. – Randyaa Jul 30 '14 at 21:01

1 Answers1

3

In the other answer that you linked to inside the comments, we use the ng-repeat directive to create a new scope for the template.

Perhaps, you could mimic this behavior with your data by wrapping your parent property inside an array [...]:

controller

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.tree = {
    label:"A",
    parent:{
      label:"B",
      parent:{
          label:"C"
      }
    }
  };
});

html

<ul ng-repeat="field in [tree]" ng-include="'tree.html'"></ul>

template

<li>
  <div>{{field.label}} {{[field.parent]}}</div>
  <ul ng-if="field" ng-repeat="field in [field.parent]" ng-include="'tree.html'"></ul>
</li>

Here is the link to the plunker: http://plnkr.co/edit/7shibX0leK1TXVl5kfPc?p=preview

A better solution would be to create your own ng-include and pass your child object to it.

jpmorin
  • 6,008
  • 2
  • 28
  • 39
  • I didn't think of the inline array syntax... Thanks for that little tip. I also haven't had a chance to get back to this but I suspect your answer would work just fine. I'm also thinking a recursive directive may do the trick, not sure how to use just a template recursively without using a repeater. – Randyaa Aug 06 '14 at 02:16
  • Let me know if this solved your problem, otherwise we can figure something else. – jpmorin Aug 08 '14 at 14:55