具有延迟加载的角树指令

时间:2014-08-25 15:48:44

标签: angularjs tree lazy-loading

我们正在使用angularJS :)开始一个新项目,其中一个要求是树控件。 树控件应支持“延迟加载”,因此我们可以动态地向其添加节点,因为我们使用AJAX获取更多数据。

我在下面看到了2个指令,但我不认为支持“延迟加载” 所以在我开始自己开发之前,我问你们大家:)

我看到的2个漂亮的树指令:

https://github.com/eu81273/angular.treeview/blob/master/angular.treeview.js https://github.com/nickperkinslondon/angular-bootstrap-nav-tree

谢谢,Avi

1 个答案:

答案 0 :(得分:1)

因为AngularJS在任何逻辑之前加载指令,所以你不能很好地将它们用于递归操作,否则你可能首先不需要一个指令。

然而,一个非常令人愉快的解决方法是使用ng-include,因为它没有上述限制。然后制作一棵树非常简单。

你想要树,你有类似的东西

    <ul class="tree-container">
        <li style="margin: 5px; list-style: none;" ng-repeat="d in vm.features" ng-include="'tree_item_renderer.html'"></li>
    </ul>

那么include看起来像这样

<script type="text/ng-template" id="tree_item_renderer.html">
    <span ng-click="d.expand = !d.expand;vm.getChildNodes(d)" ng-show="!d.expand && d.hasChildren"><i class="fa fa-fw fa-plus-circle"></i></span>
    <span ng-show="d.expand && d.hasChildren" ng-click="d.expand = !d.expand;d.children=null" ><i class="fa fa-fw fa-minus-circle"></i></span> 
    <span ng-show="!d.hasChildren" style="margin-left:28px"></span>

    <ul>
        <li style="list-style:none;" ng-repeat="d in d.children" ng-model="d" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>

在控制器vm.getChildNodes(d)调用中,您可以获取当前展开节点的子节点。我扩展节点,然后实际异步地对odata上的每个节点进行计数,以确定节点是否有子节点,因此我可以显示其中一个孩子是否有自己的孩子,但当然你可以更有效地跟踪数据库,如果你有控制权(我想我会自己更新我的模型)。

请注意,我已经实现了它,因此如果您打开和关闭然后打开,它实际上会重新加载节点。当然,你不必这样做,但它使我免于必须实施重新加载/刷新按钮,而且用户不会一遍又一遍地打开/关闭树,因为他们什么都没有更好。 ;)

我所拥有的附加优势是我为一些(大多数)节点实现用户输入,例如选择它们,为它们输入一个值。我注意到如果这些只是按需提供它会更有效率&#39;在角度。