如何在angularjs中显示json

时间:2014-01-06 16:43:38

标签: javascript json angularjs

我需要帮助在angular-js选择器中显示json whos结构。我是一个有角度的新手,并且有助于将其显示为下拉并使其成为可搜索的。

[

    {
        "id":1,
        "name":"something1",
        "displayName":"something1",
        "children":[
            {
                "id":9,
                "name":"something1Child1",
                "displayName":"something1/ something1Child1",
                "children":[
                ],
                "typeId":1,
                "parentId":1
            },
            {
                "id":10,
                "name":"something1Child2",
                "displayName":"something1 / something1Child2",
                "children":[
                ],
                "typeId":1,
                "parentId":1
            }
        ]
  }

  {
        "id":2,
        "name":"something2",
        "displayName":"something2",
        "children":[
        ]
  }

]

2 个答案:

答案 0 :(得分:1)

您只需要为孩子们​​设置嵌套的ng-repeat。

<span ng-repeat="something in somethings"> 
  <h3>{{ something.name }}</h3>
  <select>
    <option ng-repeat="child in something.children"> {{ child.name }}</option>
  </select>
</span>

我猜你想如何显示它们,但我希望它可以给你一些想法。 Here is a JsBin

答案 1 :(得分:0)

JSFiddle能做你想做的吗?它采用嵌套结构并从中制作出扁平结构。然后它将使用该平面结构进行显示。

<select ng-model="selected">
    <option ng-repeat="option in tree" ng-bind-html-unsafe="option.displayName" value="{{$index}}">{{ option.displayName }}</option>
</select>

$scope.tree = [];
function buildTree(data, depth) {
    for(d in data) {
        var c = angular.copy(data[d]); //copy object
        delete c['children'];  //we dont want to copy children
        c.displayName = Array(depth*4).join("&nbsp;") + c.displayName;
        $scope.tree.push(c);
        buildTree(data[d].children, depth+1);
    }
}
buildTree($scope.data, 0);

我使用ng-bind-html-unsafe因为你想像树一样显示它,我觉得最好通过在nest选项之前添加空格来完成,这是用&nbsp;完成的。