Angular 递归

3

在Angular中创建递归有两种方法:

第一种方法使用$compile函数并手动编译内容。


链接:Angularjs:理解递归指令

compile: function(tElement, tAttr) {
        var contents = tElement.contents().remove();
        var compiledContents;
        return function(scope, iElement, iAttr) {
            if(!compiledContents) {
                compiledContents = $compile(contents);
            }
            compiledContents(scope, function(clone, scope) {
                     iElement.append(clone); 
            });
        };
    },

例子:http://jsfiddle.net/n8dPm/


第二个使用ng-include

链接:https://groups.google.com/forum/?fromgroups=#!topic/angular/TbpjE-5XEM0

<script type="text/ng-template"  id="tree_item_renderer.html">
{{data.name}}
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
<ul>
    <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
</ul>

例子:http://jsfiddle.net/brendanowen/uXbn6/8/


我的问题是:它们各自有什么优缺点?是否可能在ng-include中使用包含自定义指令的模板?

1个回答

0

我相信你错过了两个宝贵的选择。

  • 在指令的模板中使用自定义指令(是的,你可以这样做)
  • 使用插槽(https://egghead.io/lessons/angularjs-transclusion-basics),当使用指令时,使模板的一部分可配置。实际上,这就是你第一个示例所做的事情,但更容易实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接