In this tutorial I am going to share simple AngularJS directive to create tree menu. You must have seen tree menu on many control panel where you have to create nested menu – submenu – submenu and so on. These nested tree structure helps to associate list of submenu with parent menu.
Libraries
Copy the script and css into your project and add a script and link tag to your page.
<script type="text/javascript" src="/angular.treeview.js">script> <link rel="stylesheet" type="text/css" href="css/angular.treeview.css"> |
Add a dependency to your application module.
angular.module('myApp', ['angularTreeview']); |
You can use following attribute to customize tree menu.
- angular-treeview: the treeview directive.
- tree-id : each tree’s unique id.
- tree-model : the tree model on $scope.
- node-id : each node’s id.
- node-label : each node’s label.
- node-children: each node’s children.
HTML
Here is a simple example.
|
Here is the tree menu structure.
$scope.treedata = [ { "label" : "User", "id" : "role1", "children" : [ { "label" : "subUser1", "id" : "role11", "children" : [] }, { "label" : "subUser2", "id" : "role12", "children" : [ { "label" : "subUser2-1", "id" : "role121", "children" : [ { "label" : "subUser2-1-1", "id" : "role1211", "children" : [] }, { "label" : "subUser2-1-2", "id" : "role1212", "children" : [] } ]} ]} ]}, { "label" : "Admin", "id" : "role2", "children" : [] }, { "label" : "Guest", "id" : "role3", "children" : [] } ]; |
JS
If tree node is selected, then that selected tree node is saved to $scope.”TREE ID”.currentNode. By using $watch, the controller can recognize the tree selection.
$scope.$watch( 'abc.currentNode', function( newObj, oldObj ) { if( $scope.abc && angular.isObject($scope.abc.currentNode) ) { console.log( 'Node Selected!!' ); console.log( $scope.abc.currentNode ); } }, false); |
See live demo and download source code.
This awesome script developed by eu81273, Visit their official github repository for more information and follow for future updates.