1

I'm very new to angularjs. I want to load a script tag using a custom angularjs directive. Below is the example code for what I want to achieve:

angular.module('app')
  .directive('myScript', function () {
    return {
      restrict: 'E',
       template : function(e,a){
           return '<script>document.write(5 + 6);</script>';  
        }
    };
  });

So, 11 will be displayed when the directive is added in html:

<div><my-script></myscript></div>

But I couldn't manage to achieve that. So, I guess my code is wrong? Please help me with this. Thanks in advance.

Yin
  • 73
  • 1
  • 11
  • Possible duplicate of the question below ..http://stackoverflow.com/questions/27533421/how-to-load-a-script-using-custom-angular-directive – Vijay May 26 '16 at 04:05

1 Answers1

0

All right, why would you like to do it by a script tag, Yin?

You can you a built-in directive to do this. Something like ng-bind or even curly braces {{}} AngularJs will evaluate your expression and set the tag value as the result.

Example: <span ng-bind="5 + 6"></span>

Result: <span>11</span>

Whenever you need to evaluate an expression you can do this way :)

  • Thanks for the reply, Carlos. Above is just an example. If the script I want to load is more complicated, how should I load it using directives? – Yin May 26 '16 at 04:19
  • Oh, got it. So, probably you would create a controller on your directive and use javascript to insert your script tag. An alternative, you could use something like [ocLazyload](https://oclazyload.readme.io/) to get your script. :) – Carlos Henrique May 26 '16 at 04:30