简体   繁体   English

从Angular中的控制器动态地将脚本注入HTML

[英]Dynamically Inject script to HTML from controller in Angular

I'm a newbee to Angular and frontend; 我是Angular和前端的新手。 sorry if my question is simple: 很抱歉,如果我的问题很简单:

I have the following code in my controller where I'm populating $window.user data which is used in the script [2] which I added in my HTML file 我的控制器中有以下代码,我在其中填充了$window.user数据,该数据用于在HTML文件中添加的脚本[2]中

$scope.currentUser.$promise.then(function (data) {
    $window.user = {};
    $window.user.firstName= data.firstName
}

And here is the script which I added in HTML [2] 这是我在HTML [2]中添加的脚本

<script type="text/javascript" src="https://test.com/embed.js" async></script>

However my data ( $window.user.firstName ) gets passed too late after loading the script; 但是,加载脚本后,我的数据( $window.user.firstName )传递太迟了; I think I have two options: 我认为我有两种选择:

1) dynamically inject/load my script to my HTML from my controller after getting $window.user.firstName . 1)在获取$window.user.firstName之后,将脚本从控制器动态地注入/加载到HTML中。 If that's the right way, how would you do that? 如果这是正确的方法,您将如何做?

2)read $window.user.firstName on $window.onload ? 2)在$window.onload上读取$window.user.firstName

Added: It is worth mentioning if I do not populate $windows.user.firstname by promise and use some dummy data outside of that data gets used by script and works fine. 补充:值得一提的是,如果我没有按承诺填充$ windows.user.firstname,而是使用脚本之外的一些伪数据,它们可以正常工作。

I found a solution: 我找到了解决方案:

$('<script type="text/javascript" src="https://myscript/embed.js" async></script>').appendTo('body');

^ It works fine. ^效果很好。 However if you see any problem with this solution please write here. 但是,如果您发现此解决方案有任何问题,请在此处写。 Thanks! 谢谢!

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

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