Example of Angular Treeview using Data from a JSON File

JSON is one of the most popular lightweight data inter-exchange platform. It is platform independent and can easily editable without using any specific tool. Simply using Notepad you can read or write to a JSON file. Looking into this nearly all advanced third-party components supports JSON formatted data. In this regard here I am with a demo app to show you how to create Angular Treeview using data from a JSON file. This example is very helpful for the beginners of AngularJS.

Look at the example below here I have a JSON file “treeview.json” which holds the required data for my Angular Treeview. As you know to design a Treeview we required formatted data. That’s why here my JSON file has two kind of data nodes & sub-nodes. To display JSON data in a Treeview here I used $http module get() method to fetch data. After successful response from get() method assigning the response data to $scope object “items” array. showSubnodes() function is to display sub-nodes under respective parent node. In view to display items I am using UL LI elements. Using ng-repeat here I am looping the data & binding each record to li elements. 2 UL elements I used here. One for parent nodes & other one for Sub-nodes.

Example of Angular Treeview using Data

Angular Treeview

index.htm

<!DOCTYPE html>
<html ng-app="myTreeview">
<head>
<title>Angular Treeview using data from a JSON File</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script type="text/javascript">
var myTreeview = angular.module('myTreeview', []);
myTreeview.controller('treeviewCtrl', function($scope, $http) {
$http.get("treeview.json").success(function (response) {
/*After Successful Response binding the JSON data to items array in Scope object*/
$scope.items = response.treedata;
});
$scope.showSubnodes = function(item){
item.active = !item.active;
};
});
</script>
</head>
<body ng-controller="treeviewCtrl">
<ul>
<li ng-repeat="item in items" ng-click="showSubnodes(item)">
<span>{{item.node}}</span>
<ul>
<li ng-repeat="subItem in item.subnodes" ng-show="item.active">
<span>{{subItem.subnode}}</span>
</li>
</ul>
</li>
</ul>
</body>
</html>

JSON File for Angular Treeview

{"treedata":
[
{
"node": "Company",
"subnodes": [
{"subnode": "About Us"},
{"subnode": "Press Release"},
{"subnode": "Contact Us"},
{"subnode": "Our Blog"},
{"subnode": "Privacy"}
]
},
{
"node": "Services",
"subnodes": [
{"subnode": "VOIP"},
{"subnode": "Web Designing"},
{"subnode": "Photo Editing"},
{"subnode": "Audio & Video Processing"},
{"subnode": "Logo Designing"}
]
},
{
"node": "Products",
"subnodes": [
{"subnode": "CMS"},
{"subnode": "Blog Posting"},
{"subnode": "Forum Marketing"},
{"subnode": "Template Creation"}
]
}
]
}