这个问题有点奇怪,可能很难理解,但我会尽力解释一下。我不得不使用 AngularJS 重写一个移动应用程序,因为之前的版本不是真正的 SPA。这是一个 JSP 网站,其设计风格适合移动设备,使用 ajax 调用灯箱、 View 等。现在我必须为新的 AngularJS 应用程序创建新功能,并将其包含到之前的 JSP 版本(AngularJS 版本)中。尚未发布)。我不想重复执行此操作,因此我已将 AngularJS 添加到旧版本中。我已经在 body 标签上注册了一个应用程序,注册了一些 Controller ,除了一件事之外一切都很好。我的 app.js
文件中有以下内容。
var oldMobile = angular.module('oldMobile', [
'flow'
])
.config(function ($controllerProvider) {
oldMobile.controller = $controllerProvider.register;
})
.controller('MainCtrl', function ($scope) {
console.log('MainCtrl'); // this is shown in the console
})
.controller('UploadCtrl', function ($scope) {
console.log('UploadCtrl'); // this is shown in the console
})
.controller('ProfileCtrl', function ($scope) {
console.log('ProfileCtrl'); // this is NOT shown in the console
});
现在,当原始 View 加载时,MainCtrl
和 UploadCtrl
已在 HTML 中注册,但 ProfileCtrl 未注册,因为这是由灯箱提供的内容,在用户事件(单击)后动态加载。当灯箱打开时,我在 HTML 中注册了 data-ng-controller="ProfileCtrl"
,但没有注册任何内容,没有任何内容写入控制台, Controller 不起作用。我尝试通过向灯箱 HTML 添加脚本标签来注册它,如下所示
<script>
angular.module("oldMobile").controller('ProfileCtrl');
</script>
但什么也没发生。当灯箱升起/调用时,如何让我的模块注册 ProfileCtrl?
如果我没有很好地解释这一点,请告诉我,我将添加到我的描述中。
提前致谢
最佳答案
开箱即用,Angular 无法延迟加载其“工件”( Controller 、指令等)。引导后注册的任何内容都会被接受,这意味着不会引发错误,但会被依赖项注入(inject)框架默默地忽略。
解决办法有点复杂,第一次看到here并在 angular-require-lazy 中也实现了它使用 RequireJS 进行延迟加载。
延迟注册 Controller 的步骤大致如下:
从
config
block 中捕获$controllerProvider
:var app = angular.module('app',[...]); var cachedControllerProvider; app.config(function($controllerProvider) { cachedControllerProvider = $controllerProvider; });
(全局不太漂亮,但这只是演示了原理。)
使用
cachedControllerProvider
延迟注册 Controller ;不要改变普通 Controller 的注册方式:cachedControllerProvider.register('ProfileCtrl', function ($scope) { console.log('ProfileCtrl'); });
(在 Angular-require-lazy 中,我修改了 Angular 对象以透明地处理此问题;这也是您的一个选择。)
确保包含延迟 Controller 注册的任何脚本都在使用这些 Controller 的模板之前执行!
关于javascript - 无需路由即可动态添加/注册 AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28695776/