Creating Custom Directive for jsTree Plugin
Posted By : Mohit Sharma | 14-Dec-2017
Creating Custum Directive for jsTree Plugin. jsTree is a jquery plugin that provides interactive trees. It is absolutely free and opensource. You can read more about jstree plugin here https://www.jstree.com/.
But jsTree doesn't provide angularJs implementation. So if we want to use jstree plugin in AngularJs project we need to create our own directive for this purpose.
For this example we will use directive in class (ngTree); As per angularJs documentation ng-tree will be interpreted as ng-tree.
In Your html File Add following Code
In Your js File Add following Code
angular.module('sampleApplication').directive('ngTree', ['commanUtills','$compile',function (commanUtills,$compile) {
return {
restrict: 'C',
controller: ['$scope','$rootScope','$document','$element','$filter','$timeout', function($scope,$rootScope,$document,$element,$filter,$timeout) {
var element = $element;
var treeContainerId = element[0].id;
var treeId = treeContainerId.substring( 0, treeContainerId.indexOf("_"));
if(angular.isDefined(treeId))
{
// Initialize jsTree elements
var tree = element.find("#"+treeId);
/** When ready is ready
* on_ready
*/
tree.on('ready.jstree', function(event) {
var treeId = event.target.id;
$scope.$broadcast("update-check-tree",(event,treeId));
});
function callAtTimeout(event,treeId) {
$scope.$broadcast("update-check-tree",(event,treeId));
}
/** When a node is checked
* Trigger Timeout
*/
tree.on('check_node.jstree', function(event) {
var treeId = event.target.id;
$timeout( function(){ callAtTimeout(event,treeId); }, 200);
});
/** When a node is unchecked
* Trigger Timeout
*/
tree.on('uncheck_node.jstree', function(event) {
var treeId = event.target.id;
$timeout( function(){ callAtTimeout(event,treeId); }, 200);
});
$scope.$on("update-check-tree",function(e,treeId){
var tree = angular.element("#"+treeId);
var treeTags = angular.element("#"+treeId+"_tags");
var checkedNodesList = treeTags.find('.selected-node');
$scope.checkTreeMap[treeId].selectedNodesCount = checkedNodesList.length;
if($scope.checkTreeMap[treeId].selectedNodesCount > 0)
{
$scope.checkTreeMap[treeId].isValid= true;
}
else
{
$scope.checkTreeMap[treeId].isValid= false;
}
});
}
}]
}
}]);
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mohit Sharma
Mohit is a bright Web App Developer and has good knowledge of Java.