AngularJS: How to make angular load script inside ng-include?

The accepted answer won’t work from 1.2.0-rc1+ (Github issue).

Here’s a quick fix created by endorama:

/*global angular */
(function (ng) {
  'use strict';

  var app = ng.module('ngLoadScript', []);

  app.directive('script', function() {
    return {
      restrict: 'E',
      scope: false,
      link: function(scope, elem, attr) {
        if (attr.type === 'text/javascript-lazy') {
          var code = elem.text();
          var f = new Function(code);
          f();
        }
      }
    };
  });

}(angular));

Simply add this file, load ngLoadScript module as application dependency and use type="text/javascript-lazy" as type for script you which to load lazily in partials:

<script type="text/javascript-lazy">
  console.log("It works!");
</script>

Leave a Comment