Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

javascript - How to bind <script> element's src attribute in AngularJS

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

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...