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?

2
  • try github.com/ocombe/ocLazyLoad and bennadel.com/blog/… also, have you tried ng-include? Commented Dec 17, 2014 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. Commented Dec 18, 2014 at 0:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
Sure I will go with this approach? What do you mean by "Something seems a little wrong here" though?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.