3

My question is about making src in html script tag dynamic. Now, I have something like this at the bottom of the html :

<script src="https://blabla.com/assets/jxx.js"></script>

In my angular js file, I've a method to return the url prefix dynamically.

$scope.trustSrc = function(src) {
    return $sce.trustAsResourceUrl($scope.pathPrefix + src);        
};

And what I want to do is transform the src part to this:

<script type="text/javascript" src="{{trustSrc('/assets/jxx.js')}}"></script>

The prefix of the url changes depending on the environment. So I need to change it dynamically.

This method works if I put the script tag in the html's head portion. But mine should be outside of the head and at the bottom of the html.

What do you recommend to do this?

  • Not sure why you're trying to do this or how to test if my suggestion works, but have you tried ng-src instead of src: https://docs.angularjs.org/api/ng/directive/ngSrc – Mario Mucalo Aug 07 '17 at 08:45
  • I don't know why you need to have it in dynamic script tag. If there is no other reason for that, you can use this Jquery function https://api.jquery.com/jquery.getscript/ – Hristo Staykov Aug 07 '17 at 08:52
  • I came across these: https://stackoverflow.com/q/15939913/single-page-application-load-js-file-dynamically-based-on-partial-view, https://stackoverflow.com/q/12197880/angularjs-how-to-make-angular-load-script-inside-ng-include. Do either provide what you are looking for? – Brian Aug 07 '17 at 09:10
  • ng-src itself is not enough. I tried that already. But I didn't try the other solutions yet. – theYoungPadawan Aug 07 '17 at 13:56

1 Answers1

0

I'm not sure but it can be happening because of your controller's scope.

As you are using trustSrcfunction with $scopein your controller, make sure that in HTML file you are using <script></script> in controller's scope.

  • I'm using it with $scope as above. The problem is if I put that last line in html *head* portion it works , but in the *body* portion it is not working. What should I do to make it work in html body, that is my question actually. – theYoungPadawan Aug 07 '17 at 13:53