通过角度控制器显示任意嵌套的JSON

时间:2015-07-29 16:03:59

标签: javascript json angularjs

这是我试图用来向页面显示JSON的函数。我知道我一遍又一遍地宣布元素,但我似乎无法发挥作用。任何帮助都非常感谢。谢谢!

bubbleController.controller('jsonDisplay', ['$scope',   function($scope) {
    this.list = $scope.json;
    this.doc = angular.element(document);
    this.curr = null;

    this.printList = function(item) {
        if (this.curr == null){
            this.curr = this.doc;
        }
        temp = angular.element("<ul>");
        this.curr.append(temp);
        this.curr = temp;
        for (key in item){
            if (typeof item[key] === 'object'){
                this.printList(item[key]);
            }
            else{
                temp = angular.element("<li>");
                this.curr.append(temp);
                this.curr = temp;
                temp = angular.element("item[key]");
                this.curr.append(temp);
                this.curr = temp;
                temp = angular.element("<li>");
                this.curr.append(temp);
                this.curr = temp;
            }
        }
        temp = angular.element("<ul>");
        this.curr.append(temp);
        this.curr = temp;
    }    

}]);

以下是使用

的JSON示例
{
    "firstName": "Johnny",
    "lastName": "Cage",
    "women": [
        {
            "True": "Sonya"
        },
        {
            "False": "Mileena"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

使用ng-include指令递归嵌套模板没有问题。

###########################
# controller.js
###########################
module.controller(function($scope) {
    // this controller uses  "template.html"
    $scope.data = {
        field1: "hello",
        field2: {
            field3: "world"
        }
    }

    $scope.canRecurse = function(v) {
        return Array.isArray(v) || typeof v == 'object';
    };
});


###########################
# template.html
###########################

<ul>
    <li ng-repeat="(key, value) in data" ng-include="'template-helper.html'"></li>
</ul>

###########################
# template-helper.html
###########################

{{key}}

<span ng-if="!canRecurse(value)">{{value}}<span>

<ul ng-if="canRecurse(value)">
    <li ng-repeat="(key, value) in value" ng-include="'template-helper.html'"></li>
</ul>