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

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

问题描述

如何像 http://jsonviewer.stack.hu/ 使用 angular JS 那样以树状方式呈现 JSON?

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

推荐答案

您感兴趣的技术是递归指令".如果您还不知道如何编写指令,那么您应该先开始学习它.Angular JS 官方文档在解释指令 Creating Custom Directives

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 的 Recursion Helper 服务非常有用.

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

在上面的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,这使人们更容易阅读.您可以修改它以满足您的需要.演示在这里,repo 在这里

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天全站免登陆