user6767148 user6767148 - 1 year ago 54
AngularJS Question

Include javascript external file if allowed in AngularJS

I need to define for my html page that load a javascript external file only when the variable

is set to
, So I tried this code: (My page is based on AngularJS )
In html :

<script src="assets/js/slider.min.js" data-ng-if="jsallowed"></script>

In JS:

$scope.jsallowed = false;

(Note that I set the application and controller and... but I just included codes you need here.)
But the problem is, My javascript file loads yet. While it should not. How can I improve my code to prevent loading it until I set jsallowed variable to true?

Answer Source

Unfortunately that data-ng-if="jsallowed" won't do the trick you're looking for. What you can do, instead, is loading the script asynchronously directly inside your JavaScript file with something like this:

var resource = document.createElement('script'); 
resource.src = "assets/js/slider.min.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download