I 've seen lots of answers that turn a Json response to a Ul Tree structure. The thing is that all these subjects where around a nested response pointing out the relationship between parent object and child object.
I have a non nested Json response indicating the relation by reference to the objects property.
The following is part of the response:
{"id":"1","parent_id":null,"name":"Item-0"}, {"id":"2","parent_id":"1","name":"Item-1"}, {"id":"3","parent_id":"2","name":"Item-2"}, {"id":"4","parent_id":"2","name":"Item-4"}, {"id":"5","parent_id":"2","name":"Item-5"}, {"id":"6","parent_id":"2","name":"Item-6"}, {"id":"7","parent_id":"2","name":"Item-7"}, {"id":"8","parent_id":"2","name":"Item-8"}, {"id":"9","parent_id":"2","name":"Item-9"}, {"id":"10","parent_id":"1","name":"Item-3"}, {"id":"11","parent_id":"10","name":"Item-10"},
You might already noticed that the each object conects with his father through the parent_id which is conected to his parent's id.
I tried to create a custom directive to read the response and through recursion to build the Tree structure.
Till now I succeeded to only create the first level of the tree. Demo
app.directive('tree',function(){ var treeStructure = { restrict: "E", transclude: true, root:{ response : "=src", Parent : "=parent" }, link: function(scope, element, attrs){ var log = []; scope.recursion = ""; angular.forEach(scope.response, function(value, key) { if(value.parent_id == scope.Parent){ this.push(value); } }, log); scope.filteredItems = log; scope.getLength = function (id){ var test = []; angular.forEach(scope.response, function(value, key) { if(value.parent_id == id){ this.push(value); } }, test); if(test.length > 0){ scope.recursion = '<tree src="scope.response" parent="'+id+'"></tree>'; } return scope.recursion; }; }, template: '<ul>' +'<li ng-repeat="item in filteredItems">' +'{{item.name}}<br />' +'{{getLength(item.id)}}' +'</li>' +'<ul>' }; return treeStructure; }); app.controller('jManajer', function($scope){ $scope.information = { legend : "Angular controlled JSon response", }; $scope.response = [ {"id":"1","parent_id":null,"name":"Item-0"}, {"id":"2","parent_id":"1","name":"Item-1"}, {"id":"3","parent_id":"2","name":"Item-3"}, {"id":"4","parent_id":"2","name":"Item-4"}, {"id":"5","parent_id":"2","name":"Item-5"}, {"id":"6","parent_id":"2","name":"Item-6"}, {"id":"7","parent_id":"2","name":"Item-7"}, {"id":"8","parent_id":"2","name":"Item-8"}, {"id":"9","parent_id":"2","name":"Item-9"}, {"id":"10","parent_id":"1","name":"Item-2"}, {"id":"11","parent_id":"10","name":"Item-10"}, ]; });
Is there any one who could show me how to convert this kind of array to Tree structure through recursion?