1

I'm quite new in AngularJS, so my question can be very trivial, but I haven't found any answer in the web which could me help.

Having data in json form, like:

{
    "Part 1": {
        "Group 1": {
            "Link 1": "href1",
            "Link 2": "href2"
        },
        "Group 2": {
            "Link 3": "href3"
        }
    },
    "Part 2": {
        "Link 4": "href4",
        "Link 5": "href5",
        "Link 6": "href6"
    }
}

I would like to present it in a tree form. For example like:

1. Part 1
    a. Group 1
        - Link 1
        - Link 2
    b. Group 2
        - Link 3
2. Part 2
    - Link 4
    - Link 5
    - Link 6

The leafs of the tree represent links which can be clicked. There can be one or two levels of nesting, so it may be a bit problematic.

Is this possible to do it using ngRepeat directive or any other way from AngularJS?

zmark
  • 127
  • 2
  • 12
  • Have a boolean parameter(isGrouping) in your JSON response which will allow you to differentiate whether grouping is there or not. – Sai Feb 19 '14 at 16:30
  • I know that it will be easier having this parameter but I I'm not allowed to change the json message structure. – zmark Feb 21 '14 at 21:31

2 Answers2

0

Using a directive will be perfect, but using only ng-repeat won't make it IMHO.

You will need a recursive directive. There are multiple way to achieve what you want described in this thread (In it, the nicest way is the one described by Mark Lagendijk).

Community
  • 1
  • 1
ThomasC
  • 7,915
  • 2
  • 26
  • 26
0

Using a directive is definitely the more appropriate solution, but you can use ng-repeat if you want (although it isn't the most elegant solution), see fiddle: http://jsfiddle.net/ADukg/4764/

You can use something like this:

<div ng-controller="MyCtrl">
  <div ng-repeat="(item, children) in data">
      {{item}}
      <div ng-repeat="(child, moreChildren) in children">
          <div class="child" ng-show="isGroup(child)">
              {{child}}
              <div class="leaf" ng-repeat="(leaf, leafValue) in moreChildren">
                  {{leaf}} - {{leafValue}}
              </div>
          </div>
          <div class="leaf" ng-show="!isGroup(child)">
              {{child}} - {{moreChildren}}              
          </div>
      </div>            
    </div>
</div>

With a basic checker:

$scope.isGroup = function(item) {
    return item.indexOf('Group') == 0;      
};
Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • Thanks. It's a good solution for me because I can assume that the tree has no more than 3 levels. Recursion is not needed in my case but it could be used. The condition isGroup is not very useful because "Group" is not fixed phrase. But I used another check which is sufficient for my case: typeof item == 'string'; – zmark Feb 21 '14 at 21:27