Friend
Friend

Reputation: 79

AngularJS Bootstrap Collapsable Treeview

I'm attempting to work the selected answer over at this Stack Overflow question into my AngularJS app. In particular, the JQuery code block

$(function () {
    $('.tree li:has(ul)').addClass('parent_li').find('>span').attr('title', 'Collapse this tree');
    $('.tree li.parent_li >span').click(function (e) {
        console.log("test");
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide('fast');
            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }
    e.stopPropagation();
    });
});

It appears to work for the first line, as the spans I'm using do have "Collapse this tree" as their tooltip. However, the console.log statement is never fired. I've tried inspecting the element through the browser debugger and all looks fine. I've tried adding the angularJS-generated classes into the JQuery above, as well as tried both $().click and $().on('click') functionality but neither seemed to work.

I also tried toying around with ng-click and just putting this manually on each span but once I got inside the JQuery it had no idea which element had pressed it even through I was passing the ID through the function parameters.

Has anyone had any luck getting this to work with Angular?

I've seen a few places suggest directives for recursively managing the trees but my tree structure doesn't necessarily lend itself to automation since it's based off of our object model.

Upvotes: 0

Views: 1233

Answers (1)

Jay
Jay

Reputation: 452

Here's a plunkr using the answer mentioned in my comment that handles a collapsing tree.

I basically just added collapsing to the directive template:

<div>
  <span 
    ng-if="item.children && item.children.length" 
    ng-click="item.hideChildren = !item.hideChildren">{{item.hideChildren ? '+' : '-'}}
  </span>
  <span>{{item.label}}</span> 
  <ul ng-if="item.children && item.children.length" ng- hide="item.hideChildren">
    <li ng-repeat="child in item.children">
      <tree-node item="child"></tree-node>
    </li>
  </ul>
</div>

Upvotes: 2

Related Questions