AngularJS Tree View Control

Did I mention that I love AngularJS? Oh, yes I did, on my previous post. Well, in case you didn’t believe me, this time I would like to share yet another small solution with AngularJS. By the way, I forgot to mention that I also use the awesome Twitter Bootstrap CSS framework, along with the also awesome Font Awesome font icons.

I made this simple tree view directive to simulate a file explorer. There was some more functionality specific to the project but I removed it for this demo. I intend to work a little bit more to make it into a more generic, configurable solution (suggestions accepted). In order to use it, you just need to add the necessary JavaScript and CSS files and drop the following HTML code in your page:

<div tree-view="structure" tree-view-options="options"></div>

Where structure is the JSON model containing the folders and files, and options is the tree view configuration (optional). If you don’t provide any, the default configuration is used.

The configuration options object currently accepts the following values:

Param Type Default Details
foldersProperty String "folders" Name of the property that contains the folders array in your model.
filesProperty String "files" Name of the property that contains the files array in your model.
displayProperty String "name" Name of the property that contains the name to be display both for files and folders.
collapsible Boolean true Whether or not the nodes are collapsible. If false, the nodes will always be expanded.
onNodeSelect function (Object, Array) undefined A callback function that is executed whenever a folder/file is selected. The first argument passed to the function is the actual node from the model, and the second argument is a dynamically generated array of all the ancestor nodes. This is useful to display breadcrums for the selected path.

The following is an example model and configuration that can be supplied to the tree view:

$scope.structure = { folders: [
    { name: 'Folder 1', files: [{ name: 'File 1.jpg' }, { name: 'File 2.png' }], folders: [
        { name: 'Subfolder 1', files: [{ name: 'Subfile 1' }] },
        { name: 'Subfolder 2' },
        { name: 'Subfolder 3' }
    ]},
    { name: 'Folder 2' }
]};

$scope.options = {
    onNodeSelect: function (node, breadcrums) {
        $scope.breadcrums = breadcrums;
    }
};

The result should be similar to this:

Untitled

The directive is recursive, so it should be able to handle any number of hierarchy levels (in theory). Source code in GitHub.

Update (8/28/2014): Added option mapIcon, which expects a function that takes a file node as the argument and must return a custom icon class (String). Sample usage included.