title: Injecting runnable JavaScript dynamically with an Angular directive
body: <p>I've been trying all day to dynamically load a script tag with JavaScript in it from an API call with a custom Angular directive. I'm getting a big error that says the first character in the string of JavaScript code is unexpected. Here is my code...</p>
  
  <p>Controller:</p>
  
  <pre><code>var html = '&lt;div id="donutchart" style="width: 200px; height: 200px;"&gt;&lt;/div&gt;';
  var javascript = 'google.load("visualization", "1", {packages:["corechart"]});google.setOnLoadCallback(drawChart); ' +
              'var drawChart = function() {' +
              'var data = google.visualization.arrayToDataTable(' +
              '[["Task", "Hours per Day"],["Work", 11],["Eat",2],["Commute",  2],["Watch TV", 2],["Sleep",    7]]);' +
              'var options = {title: "My Daily Activities",pieHole: 0.4};' +
              'var chart = new google.visualization.PieChart(document.getElementById("donutchart"))};' +
              'chart.draw(data, options)';
  
  $scope.html = $sce.trustAsHtml(html);
  $scope.javascript = $sce.trustAsJs(javascript);
  </code></pre>
  
  <p>HTML: </p>
  
  <pre><code>&lt;bind-javascript html="{{html}}" javascript="{{javascript}}"&gt;&lt;/bind-javascript&gt;
  </code></pre>
  
  <p>Directive: </p>
  
  <pre><code>(function() {
  var directive = function() {
      return {
          restrict: 'E',
          scope: {
              html: '@',
              javascript:'@'
          },
          replace: false,
          template: '&lt;div class="binded-javascript" id="donutchart" ng-bind-html="html"&gt;&lt;/div&gt;',
          link:function($scope, element, attr) {
              var script = angular.element(document.createElement('script'));
              var source = $sce.trustAsJs($scope.javascript);
              script.innerHTML = source;
              angular.element(document.getElementsByTagName('head')[0]).append(script);
          }
      };
  };
  
  angular.module('app')
      .directive('bindJavascript', directive);
  }());
  </code></pre>