Ingmar
Ingmar

Reputation: 1447

How to add data-attributes to a Bootstrap Treeview?

I am using bootstrap-treeview 1.2.0 (from Jon Miles).

My goal is to add custom data-attributes to my list items' markup, e.g.

<li class="list-group-item node-tree" data-id="100" data-type="user" ...>

I tried to follow these instructions see here and here is part of my JSON:

[{"text":"Root","icon":null,"data-id":1,"data-type":"branch","nodes":[{"text":"Steve","icon":null,"data-id":17, "data-type":"user","nodes":...

To me the JSON looks good. But none of my data-attributes gets rendered in the markup.

Any ideas?

Upvotes: 0

Views: 8662

Answers (2)

Uğur Kaya İsmaİl
Uğur Kaya İsmaİl

Reputation: 71

Sorry, I see it's too late. I searched about this and couldn't find anything. But you can change bootstrap-treeview.js file a bit. There is some attribute set code in buildTree function. It's looking like this:

    Tree.prototype.buildTree = function (nodes, level) {

        if (!nodes) return;
        level += 1;

        var _this = this;
        $.each(nodes, function addNodes(id, node) {

            var treeItem = $(_this.template.item)
                .addClass('node-' + _this.elementId)
                .addClass(node.state.checked ? 'node-checked' : '')
                .addClass(node.state.disabled ? 'node-disabled': '')
                .addClass(node.state.selected ? 'node-selected' : '')
                .addClass(node.searchResult ? 'search-result' : '') 
                .attr('data-nodeid', node.nodeId)
                .attr('style', _this.buildStyleOverride(node));
......................SOME CODES ........SOME CODES..........................}

You can add :

.attr('data-type', node.dataType)
.attr('data-id', node.dataId)

And then change the object(json) like this:

[{"text":"Root","icon":null,"dataId":1,"dataType":"branch","nodes":
[{"text":"Steve","icon":null,"dataId":17, "dataType":"user","nodes":...

Upvotes: 7

Jonathan Shay
Jonathan Shay

Reputation: 946

The link provided simply instructs how to expand the node object with additional properties. There is no correlation between a node's properties and the attributes assigned in HTML.

You might want to do something like this:

var allNodes = $('#tree').treeview('getNodes);
$(allNodes).each(function(index, element) {
    $(this.$el[0]).attr('data-attribute-name', this.data-attribute-name);
});

Upvotes: 0

Related Questions