title: How to render a directive to a HTML string in Angular JS?
body: <p>Using Angular, I am trying to dynamically generate an svg using a directive.</p>
  
  <p>I have a directive called <code>&lt;svg-directive&gt;</code> with a template containing a valid xml svg definition with some scope variables. If I include <code>&lt;svg-directive&gt;&lt;/svg-directive&gt;</code> in my template it displays just fine.</p>
  
  <p>In my page controller, I would like to retrieve a compiled string of my svg directive with all the scope variables populated (the goal is to send this string to a REST API with a HTTP POST).</p>
  
  <p>In my controller I have the following code:</p>
  
  <pre><code>var compiled = $compile("&lt;svg-directive&gt;&lt;/svg-directive&gt;")($scope);
  
  $timeout(function() {
      var svgEl = compiled[0].querySelector("svg");
      var svgStr = new XMLSerializer().serializeToString(svgEl);
      console.log(svgStr);
  }, 0);
  </code></pre>
  
  <p>When I load this controller the first time, I get:</p>
  
  <pre><code>TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.
  </code></pre>
  
  <p>On the <code>var svgEl = compiled[0].querySelector("svg");</code> line.</p>
  
  <p>However, once on the page, if I click refresh the error goes away and the <code>svgStr</code> contents is successfully logged to the screen.</p>
  
  <p>My question is: How can I get the directives HTML to serialize correctly the first time the controller is loaded?</p>
  
  <p>PS. Any suggestions to improving my approach to getting the directives rendered HTML are also welcome.</p>