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.

1

1 Answer 1

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 :)

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

2 Comments

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?
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 to get your script. :)

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.