Search code examples
javascriptangularjsangularjs-directiveangular-uiangular-ui-bootstrap

Angular JS render JSON in tree like format


How do I render JSON in tree like way just like http://jsonviewer.stack.hu/ does using angular JS?


Solution

  • The technique you are interested in is 'recursive directive'. If you don't know how to write a directive yet, then you should start learning it first. The official Angular JS doc got a lot better in explaining about directive Creating Custom Directives

    Once you know how to write custom directive, you can learn about recursive directive. I found this Google Groups thread helpful: Recursive directives. Especially, I found Mark Lagendijk's Recursion Helper service in that thread very useful.

    Make sure to checkout the examples there. Some relevant examples for you are:

    plnkr
    jsfiddle

    In the jsfiddle example above, take a look at:

    module.directive("tree", function($compile) {
        return {
            restrict: "E",
            transclude: true,
            scope: {family: '='},
            template:       
                '<ul>' + 
                    '<li ng-transclude></li>' +
                    '<p>{{ family.name }}</p>' + 
                    '<li ng-repeat="child in family.children">' +
                        '<tree family="child"></tree>' +
                    '</li>' +
                '</ul>',
            compile: function(tElement, tAttr, transclude) {
                var contents = tElement.contents().remove();
                var compiledContents;
                return function(scope, iElement, iAttr) {
                    if(!compiledContents) {
                        compiledContents = $compile(contents, transclude);
                    }
                    compiledContents(scope, function(clone, scope) {
                             iElement.append(clone); 
                    });
                };
            }
        };
    });
    

    Some of the code above is abstracted away by Mark Lagendijk's Recursion Helper service I mentioned above.

    Lastly, I implemented angular-json-human, which renders JSON in a nested table structure, which makes it easier for human to read. You can modify it to suit your need. The demo is here and the repo is here

    Hope this helps!