JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<div ng-app="myApp">
<fieldset class="regulated" ng-controller="jManajer">
<tree src="response" parent=""></tree>
</fieldset>
</div>
CSS
.regulated{
width : 20em;
}
JavaScript
var app = angular.module('myApp',[]);
app.directive('tree',function(){
var treeStructure = {
restrict: "E",
transclude: true,
root:{
response : "=src",
Parent : "=parent"
},
link: function(scope, element, attrs){
//helper function
unflatten = function( array, parent, tree ){
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : { id: "0" };
var children = _.filter( array, function(child){ return child.parent_id == parent.id; });
if( !_.isEmpty( children ) ){
if( parent.id == "0" || parent.id == null ){
tree = children;
}else{
parent['children'] = children
}
_.each( children, function( child ){ unflatten( array, child ) } );
}
console.log(tree)
return tree;
}
scope.filteredItems = unflatten(scope.response);
console.log(scope.filteredItems)
scope.prettify = function (items){
return (JSON.stringify(items, null, " "))
};
},
template:
'<pre>'
+'{{prettify(filteredItems)}}'+
'<pre>'
};
return treeStructure;
});
app.controller('jManajer', function($scope){
$scope.information = {
legend : "Angular controlled JSon response",
};
$scope.response = [
{"id":1,"parent_id":0,"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"},
];
});