如何绑定<script>AngularJS 中元素的 src 属性 [英] How to bind <script> element's src attribute in AngularJS
问题描述
我正在尝试将 HTML <script>
元素的 src
属性绑定到我的 angular 控制器中的变量,以便我可以从控制器更新它而无需处理任何 UI.
I am trying to bind the src
attribute of an HTML <script>
element to a variable in my angular controller, so that I can update it from controller without dealing with any UI.
到目前为止,我已经尝试了所有这些选项:
So far I've tried all these options:
<script type="text/javascript" ng-src="{{sourceUrl}}"></script>
<script type="text/javascript" src="{{sourceUrl}}"></script>
<script type="text/javascript" ng-src="sourceUrl"></script>
在我的控制器中,我有:
In my controller I have:
$scope.sourceUrl = "https://<some url goes here>";
在设置 $scope.sourceUrl 后在浏览器中运行页面时,没有对 sourceUrl 的传出请求,所以我确定我做错了什么.有什么想法吗?
When running the page in the browser after the $scope.sourceUrl gets set there is no outgoing request to sourceUrl, so I am sure I am doing something wrong. Any ideas?
我发现了几篇关于 <img>
元素的 src
属性的帖子,ng-src
应该像他们说的那样工作,但我猜测 有什么不同.
I found several posts about src
attribute of <img>
element, and ng-src
should work as they say, but I guess <script>
is somehow different.
推荐答案
很遗憾,您不能以这种方式使用 Angular.Angular 仅在页面加载和构建之后处理网页,此时 标签已被处理一次(脚本标签只运行一次).其他标签(例如
img
)会在页面加载后其属性发生变化时更改屏幕的视觉外观……但如前所述,脚本仅被处理一次并且即使在页面加载期间以及在 Angular 获得控制之前.
Unfortunately, you can not use Angular in this way. Angular processes the web page only after the page has been loaded and built by which time the <script>
tag has been processed its one time (script tags are only ever run once). Other tags such as img
will change the visual appearance of the screen when their properties change after the page has loaded ... but as mentioned, the script is only processed once and even then during page load and before Angular can ever get control.
这篇关于如何绑定<script>AngularJS 中元素的 src 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!