How to bind <script> element's src attribute in AngularJS
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.
You could have added it dynamically to the end of the body from within the controller:
$("<script>").attr({src: $scope.sourceUrl}).appendTo("body");
Adding my solution as an answer per @Jonathan's suggestion.
(function (ng) {
// Retrieve main app module
var appModule = angular.module('appModule');
// This directive appends a child <script> element to an element with 'my-container' attribute.
// This is needed for 'src' attribute generation and script evaluation of some object after the
// page has been loaded.
appModule.directive('myContainer', ['$log', 'MvcModelService', function ($log, MvcModelService) {
return {
restrict: 'A',
scope: false,
link: function (scope, elem, attrs) {
var s = document.createElement("script");
s.type = "text/javascript";
var JSObjectName = "JSObject";
// Just a random number ...
var randomNumber = Math.floor(Math.random() * Number.MAX_VALUE);
// flowId is a UUID representing current session.
var flowId = MvcModelService.FlowId;
// Construct the url where the object contents will be loaded from:
var Url = MvcModelService.UrlPrefix + "Get" + whatever + "/" + JSObjectName +
"someOtherStuffDepending on flowId and randomNumber";
s.src = Url;
$log.info("Adding script element to MyContainer with source url: " + Url);
elem.append(s);
}
};
}]);
}(angular));
And the view snippet follows:
<div id="JSObjectScript" style="display: inline" my-container />