user6767148 user6767148 - 2 months ago 8
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

$scope.jsallowed
is set to
true
, 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

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:

<script>
var resource = document.createElement('script'); 
resource.src = "assets/js/slider.min.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
</script>