Angular.js Treeview with examples

Angular.js TreeView is for showing hierarchical information which starts from the root item. TreeView directive which comes with a built in option to display customizable checkboxes to each item. Advantage of TreeView is that you can display large amounts of data in less area. It works in a parent child relationship. We will look at an example of TreeView using data from item objects under $scope. We have three files, index.html, treeview.html, app.js. Index.html where we refer to the CDN link of AngularJS library. The template for treeview will be in the treeview.html file. In the App.js file the logic to create a treeview in Angular is written. Countries and states are assigned as items in $scope. 

Example of Angular.js TreeView.

  • INDIA

    • Assam

    • Chhattisgarh

    • Sikkim

    • Maharashtra

    • Madhya Pradesh


  • UNITED STATES

  • PAKISTAN

    •     Peshawar

    •     Lahor

    •     Karachi

    •     Islamabad


Index.html

<!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.html

<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'

};

});