title: Angularjs: understanding a recursive directive
body: <p>I found a great tree directive here. Original: <a href="http://jsfiddle.net/n8dPm/" rel="nofollow noreferrer">http://jsfiddle.net/n8dPm/</a></p>
  
  <p>I have been trying to understand the functioning of it through couple of other SO questions, <a href="https://stackoverflow.com/questions/19120386/angularjs-transclude-directive-template">1</a>,<a href="https://stackoverflow.com/questions/19124986/angularjs-attaching-a-click-event-in-directive">2</a> . I couldn't quite understand how the recursive calls to render the tree directive work. Mainly the compile function</p>
  
  <ol>
  <li>When all the compile function called?</li>
  <li>When is the $compile function  cached in the varibale <code>compiledContents</code> (is this the link function?), and when is it appends? Why it is not append always?</li>
  </ol>
  
  <p>--</p>
  
  <pre><code>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); 
                  });
              };
          },
  </code></pre>