3

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?

1

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

7 Comments

How about wrapping this code in directive, doing some whatever magic there? Why downvoted, just curious, because not angular way suggested? Can we play the $injector here, to dynamically add stuff?
@user3198882, there is no Angular way to do this trick. Not sure why you down voted my suggestion but I can assure this works and it's quite common to see this syntax around. Also, this is what Google suggests when importing its Analytics library. Of course, you can wrap that inside an Angular directive, I just highlighted the JavaScript code you need to run to do the trick.
It wasn't me, who downvoted, I just asked why someone did it, still interesting to me as well :)
Thank you too much, I tried this in an non-angularjs page and It worked well, I want to know, Will pure javascript codes work in angularjs-based pages as well? UPDATE: I tried it in my AngularJS page and It worked well!
That's right, Angular is a JavaScript framework which means you can use pure JavaScript code in any Angular project. Angular just add/extend native JavaScript functionalities to do more with less.
|

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.