Created
September 30, 2015 07:43
-
-
Save matthewbednarski/59ab864ea4ee0445f55f to your computer and use it in GitHub Desktop.
an angular 1.x directive for bootstrap-treeview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
/** | |
* A [bootstrap-treeview](https://github.com/jonmiles/bootstrap-treeview) directive. | |
* | |
* requires: | |
* bootstrap-treeview: v 1.2.0 | |
* | |
*/ | |
var app = angular.module('mcbTree', []) | |
.directive('tree', ['$parse', Tree]); | |
function Tree($parse) { | |
return { | |
restrict: 'E', | |
scope: { | |
id: '@', | |
selected: '&', | |
tree: '=', | |
filtered: '=', | |
search: '@' | |
}, | |
replace: true, | |
transclude: false, | |
compile: function(element, attrs) { | |
var modelAccessor = $parse(attrs.ngModel); | |
var id = attrs.id; | |
if (id === undefined || id === '') { | |
id = 'tree'; | |
} | |
var template = '<div>' + | |
'<div class="tree" id="__id__" ng-model="tree" ng-click="toTree(tree);"></div>' + | |
'</div>'; | |
template = template.replace(/__id__/g, id); | |
var newElem = $(template); | |
element.replaceWith(newElem); | |
return function(scope, topDiv, attrs, controller) { | |
var jqueryTree = $('.tree:first'); | |
scope.$watch(function() { | |
return scope.search; | |
}, function(n, o) { | |
if (n !== o) { | |
jqueryTree.treeview('search', [n, { | |
ignoreCase: true, | |
exactMatch: false, | |
revealResults: true | |
}]); | |
} | |
}, true); | |
scope.$watch(function() { | |
return scope.tree.length; | |
}, function(n, o) { | |
scope.search = ''; | |
jqueryTree.treeview({ | |
data: scope.tree | |
}); | |
jqueryTree.on('searchComplete', function(event, data) { | |
var f = _.chain(_.keys(data)) | |
.map(function(k){ | |
return data[k]; | |
}) | |
.value(); | |
_.remove(scope.filtered); | |
_.assign(scope.filtered, f); | |
}); | |
jqueryTree.on('nodeSelected', function(event, data) { | |
scope.selected({ | |
node: data | |
}); | |
scope.$apply(); | |
}); | |
}, true); | |
}; | |
} | |
}; | |
} | |
})(window.jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment