动态添加/注册AngularJS控制器,无需路由

Dynamically adding/registering an AngularJS Controller without routing

本文关键字:路由 控制器 AngularJS 添加 注册 动态      更新时间:2024-04-28

这个问题有点奇怪,可能很难理解,但我会尽力解释。我不得不使用AngularJS重写一个移动应用程序,因为以前的版本不是真正的SPA。这是一个JSP网站,其风格适合于使用ajax调用灯箱、视图等的移动设备。现在我必须为新的AngularJS应用程序创建新功能,并将其包含在以前的JSP版本中(AngularJS版本尚未发布)。我不想做两次,所以我在旧版本中添加了AngularJS。我在body标签上注册了一个应用程序,注册了一些控制器,除了一件事,一切都很好。我的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
});

现在,当原始视图加载MainCtrlUploadCtrl时,它们在HTML中注册,但ProfileCtrl没有注册,因为这是由用户事件(单击)后动态加载的灯箱提供的内容。当我在HTML中注册data-ng-controller="ProfileCtrl"的灯箱打开时,没有注册任何内容,也没有向控制台写入任何内容,控制器不起作用。我试着通过在lightbox HTML中添加一个脚本标记来注册它,就像一样

<script>
  angular.module("oldMobile").controller('ProfileCtrl');
</script>

但什么也没发生。当灯箱被提起/调用时,我如何让我的模块注册ProfileCtrl?

如果我没有很好地解释,请告诉我,我会补充我的描述。

提前感谢

开箱即用,Angular不能延迟加载其"工件"(控制器、指令等)。自举后注册的任何内容都会被接受,这意味着不会抛出任何错误,但依赖注入框架会默默忽略。

这个解决方案有点复杂,第一次在这里看到它,并用RequireJS在angular require lazy for lazy加载中实现了它。

延迟注册控制器的步骤大致如下:

  1. config块捕获$controllerProvider

    var app = angular.module('app',[...]);
    var cachedControllerProvider;
    app.config(function($controllerProvider) {
        cachedControllerProvider = $controllerProvider;
    });
    

    (全球并不漂亮,但这只是证明了原理。)

  2. 使用cachedControllerProvider延迟注册控制器;不要改变正常控制器的注册方式:

    cachedControllerProvider.register('ProfileCtrl', function ($scope) {
        console.log('ProfileCtrl');
    });
    

    (在angular require lazy中,我修改angular对象以透明地处理此问题;这也是您的一个选项。)

  3. 确保在使用这些控制器的模板之前执行任何包含惰性控制器注册的脚本