3

There are two ways to create a recursion in angular

the first one uses the $compile function and manually compiles the content


link: Angularjs: understanding a recursive directive

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); 
            });
        };
    },

example: http://jsfiddle.net/n8dPm/


the second one uses ng-include

link: 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>

example: http://jsfiddle.net/brendanowen/uXbn6/8/


my question is: what are the pros and cons for both of them and is it possible to use a template that includes a custom directive in ng-include?

Community
  • 1
  • 1
John Smith
  • 615
  • 4
  • 15

1 Answers1

0

I believe you are missing two valuable alternatives.

  • Use custom directives in the template of a directive (yes you can do this)
  • Use transclusion (https://egghead.io/lessons/angularjs-transclusion-basics) to have a part of the template configurable when using the directive. In fact, this does what your first example does, but easier.
Pieter Herroelen
  • 5,977
  • 2
  • 29
  • 37