通过Angular 2中的所有组件加载脚本 [英] Load scripts through all components in Angular 2
问题描述
我一直在使用Angular 2和 AdminLTE ,它需要运行一些脚本来正确加载。所以我已将它们添加到我的 .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屋!