通过 Angular 2 中的所有组件加载脚本 [英] Load scripts through all components in Angular 2
问题描述
我一直在使用带有 AdminLTE 的 Angular 2,它需要运行一些脚本才能正确加载.所以我在我的 .anglular-cli.json 中添加了它们:
I have been using Angular 2 with AdminLTE which needs to run some scripts to load properly. So I have added them in in my .anglular-cli.json:
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"../node_modules/admin-lte/dist/js/adminlte.min.js",
"../node_modules/moment/min/moment.min.js"
],
不幸的是,这并不总是有效.页面第一次加载正常,但是当我路由到另一个页面时,不会为组件模板重新加载脚本.
Unfortunately, this does not work all time. The page loads fine the first time but when I route to another page, scripts are not reloaded for the component template.
我找不到任何关于此的信息,这让我感到非常惊讶,因为我认为这将是一个普遍的问题!我可能会完全迷失于此!
I could not find any information about this which is very surprising for me since I thought it would be a general problem! I might be totally lost with this!
推荐答案
您可以在每次需要时在 DOM 中删除和重新创建脚本元素,如下所示:
You can remove and recreate your script elements in DOM every time you need, like this:
document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);
我在 GitHub 上发布了一个问题,我解释了如何去做.
I posted a question in GitHub where I explain how to do it.
这篇关于通过 Angular 2 中的所有组件加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!