1

I am trying to load a script in my custom angular directive. Right now, it is simply adding script tag in DOM but it is not loading it.

angular.module('myApp')
  .directive('rjHeader', function () {
    return {
      restrict: 'E',
       template : function(e,a){
           return '<script type="text/javascript" charset="utf-8" src="https://my.web.com/path/' + a.locale + '/some.js" ></script>';  
        }
    };
  });

And in html

<div rj-Header locale="en_US"></div>

When opening the page in browser, it correctly adds the intended script.

<script type="text/javascript" charset="utf-8" src="https://my.web.com/path/en_US/some.js" ></script> 

But this doesn't actually loads this .js file. If I simple copy paste this line to my html then it works as expected. How can I inject script using custom angular directive?

Rakesh Juyal
  • 35,919
  • 68
  • 173
  • 214
  • try https://github.com/ocombe/ocLazyLoad and http://www.bennadel.com/blog/2554-loading-angularjs-components-with-requirejs-after-application-bootstrap.htm also, have you tried ng-include? – SoluableNonagon Dec 17 '14 at 19:48
  • up voted since IMHO it is useful for directives to be able to inject scripts in few cases (not always). One case would be an isolated self-packaged directive. – Aidin Dec 18 '14 at 00:26

1 Answers1

3

Something seems a little wrong here, but if you really wanted to do this you could just append a script tag to your directive's element:

app.directive('loadDirective', function() {
  return {
    restrict: 'E',
    link: function($scope, $el) {

      var script = document.createElement('script');
      script.src = '//cdnjs.cloudflare.com/ajax/libs/emojione/1.3.0/lib/js/emojione.min.js'
      $el.append(script);
    }
  }
});

Plunk

Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
  • Yeah, after a few attempts I come out with the same solution but I'd like to know why if you load a script by template you get SyntaxError: unterminated string literal – Whisher Dec 17 '14 at 20:39
  • Sure I will go with this approach? What do you mean by "Something seems a little wrong here" though? – Rakesh Juyal Dec 17 '14 at 22:36
  • @RakeshJuyal it feels odd to load a script tag in a directive when there are so many other ways to get JS on a page (RequireJS, Curljs, just doing it in vanilla js). That said, I am not familiar with your use case, so that feeling may be unfounded. – Nick Tomlin Dec 17 '14 at 23:26