Angular JS以树格式呈现JSON [英] Angular JS render JSON in tree like format

查看:647
本文介绍了Angular JS以树格式呈现JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用角度JS,像 http://jsonviewer.stack.hu/ 那样在树中呈现JSON?

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

推荐答案

您感兴趣的技术是递归指令。如果您还不知道如何编写指令,那么您应该先开始学习它。 Angular JS官方文档在解释有关创建自定义指令的指令方面做得更好

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

一旦知道如何编写自定义指令,就可以了解递归指令。我发现此Google网上论坛主题非常有用:递归指令。特别是,我发现 Mark Lagendijk的递归助手服务非常有用。

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 < br>
jsfiddle

在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); 
                });
            };
        }
    };
});

上面的一些代码是由我上面提到的Mark Lagendijk的Recursion Helper服务提取的。

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

最后,我实现了 angular-json-human ,它在嵌套的表结构中呈现JSON,这使人们更容易阅读。您可以根据需要进行修改。该演示是此处,回购是这里

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

希望这有帮助!

这篇关于Angular JS以树格式呈现JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆