Treeview is a Classical fashion to display hierarchy of data. In less area using Treeview we can show large amount of data. Treeview works under parent child relationship. Parent is called node & the sub-items are called Child’s. Whether you do maintain a JSON file or Database AngularJS Treeview required relationship in Data.
In the below example I created an AngularJS Treeview using data from items object under $scope. Here Countries are the nodes & States are the Child’s. To design this demo here 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.
Angularjs Treeview Example
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' }; });