user3166150
user3166150

Reputation:

How to display json in angularjs

I need help displaying json whos structure is like this in angular-js selector. I am a new to angular and and help displaying this as a drop down and making it a searchable is welcomed.

[

    {
        "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":[
        ]
  }

]

Upvotes: 0

Views: 1137

Answers (2)

Danny
Danny

Reputation: 7518

Does this JSFiddle do what you want? It takes your nested structure and makes a flat structure from it. It will then use that flat structure for display.

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

I use ng-bind-html-unsafe because you wanted to display it like a tree, I feel like that is best accomplished by adding whitespace before the nest option, which is done with the &nbsp;.

Upvotes: 0

Bertrand
Bertrand

Reputation: 13570

You just need a nested ng-repeat for the childrens.

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

I am guessing how you want to display them but i hope it can give you some ideas. Here is a JsBin

Upvotes: 1

Related Questions