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?

4
  • I think it would simplify things to reverse the tree before adding it to the scope Commented Jul 30, 2014 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. Commented Jul 30, 2014 at 19:03
  • I have drastically simplified the structure and it is coming from an existing service Commented Jul 30, 2014 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: stackoverflow.com/questions/15661289/… I could modify the data structure again, but I'd like to avoid that if I can. Commented Jul 30, 2014 at 21:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Let me know if this solved your problem, otherwise we can figure something else.

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.