I'm currently working on a web application that requires the display of a tree structure using lists. Here is the basic outline:
* Node 1
* Node 1.1
* Node 1.1.1
* Node 1.1.1.1
* Node 1.1.2
* Node 1.2
My goal is to find a solution in Angular or Bootstrap so that:
- The list initially shows up to the third layer, displaying Node 1, Node 1.1, Node 1.1.1, Node 1.1.2, and Node 1.2 (excluding Node 1.1.1.1)
- Clicking on the list-style icon toggles the node to collapse or expand
- Preferably, I would like the icon to change based on whether the item is expanded - a right arrow for items with children, a down arrow for expanded items, and a regular list item for those without children
I am new to AngularJS and still learning Bootstrap. While Angular's accordion function doesn't meet all my requirements, I believe there must be existing solutions for this common issue. Any guidance on the best approach would be greatly appreciated before I implement complex logic into my application.
HTML code:
<div ng-app="myApp" ng-controller="controller">
<my-directive></my-directive>
<table style="width: 100%"><tbody><td>
<tree items="tree"></tree>
</td></tbody></table>
</div>
Angular code:
var app = angular.module('myApp', []);
app.controller('controller', function ($scope){
$scope.tree=[{"name":"Node 1","items":[{"name":"Node 1.1","items":[{"name":"Node 1.1.1","items":[{"name":"Node 1.1.1.1","items":[]}]},{"name":"Node 1.1.2","items":[]}]},{"name":"Node 1.2","items":[]}]}];
});
app.directive('tree', function() {
return {
template: '<ul><tree-node ng-repeat="item in items"></tree-node></ul>',
restrict: 'E',
replace: true,
scope: {
items: '=items',
}
};
});
app.directive('treeNode', function($compile) {
return {
restrict: 'E',
template: '<li >{{item.name}}</li>',
link: function(scope, elm, attrs) {
if (scope.item.items.length > 0) {
var children = $compile('<tree items="item.items"></tree>')(scope);
elm.append(children);
}
}
};
});