【发布时间】:2016-03-28 14:38:14
【问题描述】:
在代码 sn-p 中,我尝试使用在包含的模板 app/foo.html 中通过指令 common.script 定义的控制器 FooCtrl。
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>
但是 AngularJS 抛出的不是控制台中预期的输出 FooCtrl:
Error: [ng:areq] Argument 'FooCtrl' is not a function [...]
我不明白为什么!模板中的代码在抛出异常之前执行,因此需要定义控制器。我该如何解决?
【问题讨论】:
标签: javascript angularjs lazy-loading angularjs-ng-include