Example to Create Treeview using AngularJS

outdoor-bonsai-tree-care

Treeview is a Classical fashion to show hierarchy of data. In less space using Treeview we can show large amount of data. Treeview builds on parent child relationship. Parent is called node & the subitems are called Child’s.

In the below example I created a sample treeview using AngularJS. Here Countries are the nodes & States are the Child’s. I have 3 files index.html, treeview.html & app.js. Index.html is the primary file where I refereed CDN link of AngularJS library. Treeview.html is the file where I am creating the template for treeview. App.js is the file where i implemented my logic’s to create a treeview using AngularJS. The module I create in app.js is treeview. Inside the module I have a directive called ngTree. In $scope I am assigning country & states as items. In items array country is the parent node when states are the child’s. In treeview.html using ng-click I am calling the function showStates(), which is in the $scope of app.js. This function helps to expand & collapse the nodes.

Example of Treeview using AngularJS

angularjs-tree

To run the below example Copy these code to notepad. Save it as index.html, treeview.html & app.js in a same folder. Before run the index.html make sure you are with Internet Connectivity.

index.htm

<!DOCTYPE html>
<html ng-app="treeview">
<head>
<meta charset="utf-8">
<title>Example to Create Treeview using AngularJS</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" src="app.js"></script>
</head>
<body>
<ng-tree></ng-tree>
</body>
</html>

treeview.htm

<ul>
<li ng-repeat="item in items" ng-click="showStates(item)">
<span>{{item.country}}</span>
<ul>
<li ng-repeat="subItem in item.states" ng-show="item.active">
<span>{{subItem.state}}</span>
</li>
</ul>
</li>
</ul>

app.js

angular.module('treeview', [])
.directive('ngTree', function() {
return {
restrict: 'E',
transclude: true,

controller: function($scope) {

$scope.showStates = function(item){
item.active = !item.active;
};

$scope.items = [
{
country: "INDIA",
states: [
{state: "Assam"},
{state: "Chhattisgarh"},
{state: "Sikkim"},
{state: "Maharashtra"},
{state: "Madhya Pradesh"}
]
},
{
country: "UNITED STATES",
states: [
{state: "Alabama"},
{state: "California"},
{state: "Hawaii"},
{state: "Michigan"},
{state: "New York"},
{state: "Washington"}
]
},
{
country: "PAKISTAN",
states: [
{state: "Peshawar"},
{state: "Lahore"},
{state: "Karachi"},
{state: "Islamabad"}
]
}
];
},
templateUrl: 'treeview.htm'
};
});