How do display a collapsible tree in AngularJS + Bootstrap

In followed example I used:

  • bootstrap
  • AngularJS recursive ng-include or (see second example) recursive directives
  • jQuery (will try to avoid in the future)

Demo 1 (ng-include) Plunker

enter image description here

From this model:

 $scope.displayTree =
            [{
            "name": "Root",
            "type_name": "Node",
            "show": true,
            "nodes": [{
                "name": "Loose",
                "group_name": "Node-1",
                "show": true,
                "nodes": [{
                    "name": "Node-1-1",
                    "device_name": "Node-1-1",
                    "show": true,
                    "nodes": []
                }, {
                    "name": "Node-1-2",
                    "device_name": "Node-1-2",
                    "show": true,
                    "nodes": []
                }, {
                    "name": "Node-1-3",
                    "device_name": "Node-1-3",
                    "show": true,
                    "nodes": []
                }]
            }, {
                "name": "God",
                "group_name": "Node-2",
                "show": true,
                "nodes": [{
                    "name": "Vadar",
                    "device_name": "Node-2-1",
                    "show": true,
                    "nodes": []
                }]
            }, {
                "name": "Borg",
                "group_name": "Node-3",
                "show": true,
                "nodes": []
            }, {
                "name": "Fess",
                "group_name": "Node-4",
                "show": true,
                "nodes": []
            }]
        }];
        [{
            "name": "Android",
            "type_name": "Android",
            "icon": "icon-android icon-3",
            "show": true,
            "nodes": []
        }];
    }

The 2nd example is based on 2 directives:

app.directive('nodeTree', function() {
      return {
        template: '<node ng-repeat="node in tree"></node>',
        replace: true,
        transclude: true,
        restrict: 'E',
        scope: {
          tree: '=ngModel'
        }
      };
});

app.directive('node', function($compile) {
  return { 
    restrict: 'E',
    replace:true,
     templateUrl: 'the-tree.html',
    link: function(scope, elm, attrs) {
    
      // ....     
     
      if (scope.node.children.length > 0) {
        var childNode = $compile('<ul ><node-tree ng-model="node.children"></node-tree></ul>')(scope)
        elm.append(childNode);
      }
    }
  };
}); 

(Added some checkboxes as well :))

Demo 2 Plunker

How it looks:

enter image description here

Leave a Comment