Problem loading AngularJS code by script-append

43 views
Skip to first unread message

Tom Brodhead

unread,
Jun 23, 2017, 12:13:07 PM6/23/17
to Angular and AngularJS discussion
If I load my Angular code directly in a script tag, it works. But if I put the code in an external file and load it by appending it to the body, it fails. Why?

In order to comply with 'strict-dynamic' CSP, no scripts must have a 'src' attribute and must simply contain JavaScript (with a SHA hash of the element in the content security policy in the server directives). I've done this in the past will all other JavaScript routines, and it's worked fine. Not so with AngularJS, which seems to need different treatment for loading.

Below is code that should reproduce the simplest possible case. Copy the ABC JavaScript code to an 'abc.js' file, and uncomment the script-append routine; it should not work. Then comment-out the script-append routine and uncomment the ABC code at the top of the script block, and the page should load correctly. Apparently, appending the ABC code to the document does not work, but presenting it within a script block in the page does. (And yes, if the abc.js file is referenced with a 'src=' in a separate script tag, then, of course, it works, but that's not what I'm trying to accomplish).
<!DOCTYPE html>
<html>
<head>
 
<title>Angular Loading Test</title>
</head>
<body>
 
<div data-ng-app="my-app" data-ng-controller="user-controls">
 
<p>{{info}}</p>
 
<button data-ng-click="click()">Click me!</button>
 
</div>
<div class=script-div></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
// TOGGLE:
// Create ABC.JS file with code below, leaving both /* */ blocks intact here
// in this script block. Then remove /* */ from one block while leaving the
// other block still commented-out. Only when the ABC code is read from this script
// block, here, will it execute (i.e., it won't execute if read from an appended script
// block, as in the bottom routine).

/*
// ABC.JS CODE & CODE FOR THIS SCRIPT BLOCK
var app = angular.module('my-app', []);
var ctor = ['$scope', function ($scope) {
 'use strict';
 $scope.info = "The button hasn't been clicked yet";
 $scope.count = 0;
 $scope.click = function () {
 $scope.count += 1;
 $scope.info = "You've clicked the button this many times: " + $scope.count;
 };
}];
app.controller('user-controls', ctor);
*/


// CODE ONLY FOR THIS SCRIPT BLOCK
/*
var script = document.createElement('script');
script.src = 'abc.js';
document.body.appendChild(script);
*/


</script>
</body>
</html>

Sander Elias

unread,
Jun 23, 2017, 12:25:36 PM6/23/17
to Angular and AngularJS discussion
Hi Tom, 

The problem is timing. If you want to do this, you have to go for manual initialization. Adding a script tag with src='abc.js' is easier ;)

Regards
Sander
Reply all
Reply to author
Forward
0 new messages