Within this snippet of code, I am attempting to utilize a controller named FooCtrl
that is defined in the included template app/foo.html
, using the directive common.script
.
angular.module('common.script', []).directive('script', function() {
return {
restrict: 'E',
scope: false,
compile: function(element, attributes) {
if (attributes.script === 'lazy') {
var code = element.text()
new Function(code)()
}
}
}
})
angular.module('app.templates', ['app/foo.html'])
angular.module("app/foo.html", []).run(function($templateCache) {
$templateCache.put("app/foo.html",
"<script data-script=\"lazy\">\n" +
" console.log('Before FooCtrl')\n" +
"angular.module('app').controller('FooCtrl', function($scope) {\n" +
"console.log('FooCtrl')\n" +
"})\n" +
"<\/script>\n" +
"<div data-ng-controller=\"FooCtrl\">app\/foo.html\n" +
"<\/div>"
)
})
angular.module('app', ['common.script', 'app.templates']).controller('ApplicationCtrl', function($scope) {
console.log('ApplicationCtrl')
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="ApplicationCtrl">
<div data-ng-include="'app/foo.html'"></div>
</div>
Despite my expectations of seeing FooCtrl
in the console output, AngularJS throws an error:
Error: [ng:areq] Argument 'FooCtrl' is not a function [...]
I am puzzled as to why this error occurs! The template's code is executed before the exception is raised, indicating that the controller should be defined. How can I rectify this issue?