简体   繁体   English

如果在AngularJS中允许,请包含javascript外部文件

[英]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 : 我需要为我的html页面定义只在变量$scope.jsallowed设置为true时才加载javascript外部文件,所以我尝试了这段代码:(我的页面基于AngularJS)在html中:

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

In JS: 在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. (请注意,我设置了应用程序和控制器......但我只是包含了您需要的代码。)但问题是,我的javascript文件已加载。 While it should not. 虽然它不应该。 How can I improve my code to prevent loading it until I set jsallowed variable to true? 在将jsallowed变量设置为true之前,如何改进我的代码以防止加载它?

Unfortunately that data-ng-if="jsallowed" won't do the trick you're looking for. 不幸的是,data-ng-if =“jsallowed”将无法完成您正在寻找的技巧。 What you can do, instead, is loading the script asynchronously directly inside your JavaScript file with something like this: 相反,你可以做的是直接在JavaScript文件中异步加载脚本,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM