您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

动态加载AngularJS控制器

动态加载AngularJS控制器

我找到了一种可能的解决方案,在引导时无需了解控制器:

// Make module Foo and store $controllerProvider in a global
var controllerProvider = null;
angular.module('Foo', [], function($controllerProvider) {
    controllerProvider = $controllerProvider;
});
// Bootstrap Foo
angular.bootstrap($('body'), ['Foo']);

// .. time passes ..

// Load javascript file with Ctrl controller
angular.module('Foo').controller('Ctrl', function($scope, $rootScope) {
    $scope.msg = "It works! rootScope is " + $rootScope.$id +
        ", should be " + $('body').scope().$id;
});
// Load html file with content that uses Ctrl controller
$('<div id="ctrl" ng-controller="Ctrl" ng-bind="msg">').appendTo('body');

// Register Ctrl controller manually
// If you can reference the controller function directly, just run:
// $controllerProvider.register(controllerName, controllerFunction);
// Note: I haven't found a way to get $controllerProvider at this stage
//    so I keep a reference from when I ran my module config
function registerController(moduleName, controllerName) {
    // Here I cannot get the controller function directly so I
    // need to loop through the module's _invokeQueue to get it
    var queue = angular.module(moduleName)._invokeQueue;
    for(var i=0;i<queue.length;i++) {
        var call = queue[i];
        if(call[0] == "$controllerProvider" &&
           call[1] == "register" &&
           call[2][0] == controllerName) {
            controllerProvider.register(controllerName, call[2][1]);
        }
    }
}
registerController("Foo", "Ctrl");
// compile the new element
$('body').injector().invoke(function($compile, $rootScope) {
    $compile($('#ctrl'))($rootScope);
    $rootScope.$apply();
});

小提琴。唯一的问题是,您需要存储,$controllerProvider并在确实不应该使用它的地方(在引导程序之后)使用它。同样,在注册之前,似乎还没有一种简单的方法来获得用于定义控制器的函数,因此我需要遍历模块_invokeQueue中未记录的。

注册指令和服务,而不是分别$controllerProvider.register简单地使用$compileProvider.directive$provide.factory。同样,您需要在初始模块配置中保存对这些引用的引用。

这是一个小提琴,可以自动注册所有加载的控制器/指令/服务,而无需单独指定它们。

其他 2022/1/1 18:13:41 有563人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶