动态加载AngularJS控制器 [英] Loading an AngularJS controller dynamically

查看:152
本文介绍了动态加载AngularJS控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的页面到了我所需要可以动态加载控制器删除一个角度应用程序。

I have an existing page into which I need to drop an angular app with controllers that can be loaded dynamically.

下面是它实现了我最好的猜测,应该如何基于API,我已经发现了一些相关的问题做一个片段:

Here's a snippet which implements my best guess as to how it should be done based on the API and some related questions I've found:

// Make module Foo
angular.module('Foo', []);
// Bootstrap Foo
var injector = angular.bootstrap($('body'), ['Foo']);
// Make controller Ctrl in module Foo
angular.module('Foo').controller('Ctrl', function() { });
// Load an element that uses controller Ctrl
var ctrl = $('<div ng-controller="Ctrl">').appendTo('body');
// compile the new element
injector.invoke(function($compile, $rootScope) {
    // the linker here throws the exception
    $compile(ctrl)($rootScope);
});

的jsfiddle 。注意,这是事件的实际链条的简化,有上述线之间的各种异步调用和用户输入

JSFiddle. Note that this is a simplification of the actual chain of events, there are various async calls and user inputs between the lines above.

当我尝试运行上面的code,这是由$编译返回的链接抛出:参数按Ctrl不是一个函数,得到了不确定。如果我理解正确的引导,它返回应了解模块的喷油器,对吧?

When I try to run the above code, the linker which is returned by $compile throws: Argument 'Ctrl' is not a function, got undefined. If I understood bootstrap correctly, the injector it returns should know about the Foo module, right?

如果不是我用做一个新的注射器 angular.injector(['NG','富']),似乎工作,但它会创建一个新的 $ rootScope 这不再是同一范围内,其中模块自举的元素。

If instead I make a new injector using angular.injector(['ng', 'Foo']), it seems to work but it creates a new $rootScope which is no longer the same scope as the element where the Foo module was bootstrapped.

我在用正确的功能要做到这一点或者是有什么我已经错过了?我知道这是不是这样做的折角方式,但我需要补充的是使用角到不旧网页的新组件,我不知道这一切时,我引导模块可能需要的组件。

Am I using the right functionality to do this or is there something I've missed? I know this isn't doing it the Angular way, but I need to add new components that use Angular to old pages that don't, and I don't know all the components that might be needed when I bootstrap the module.

更新:

我已经更新了小提琴表明我需要能够在多个控制器在不确定的点添加到页面在时间。

I've updated the fiddle to show that I need to be able to add multiple controllers to the page at undetermined points in time.

推荐答案

我已经找到了一个可能的解决方案,我并不需要知道引导之前控制器:

I've found a possible solution where I don't need to know about the controller before bootstrapping:

// 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 ,这需要循环是未记录。

Fiddle. Only problem is that you need to store the $controllerProvider and use it in a place where it really shouldn't be used (after the bootstrap). Also there doesn't seem to be an easy way to get at a function used to define a controller until it is registered, so I need to loop through the module's _invokeQueue, which is undocumented.

更新::要注册指令和服务,而不是 $ controllerProvider.register 只需使用 $ compileProvider.directive 分别和 $ provide.factory 。再次,你需要保存在初始模块配置到这些引用。

UPDATE: To register directives and services, instead of $controllerProvider.register simply use $compileProvider.directive and $provide.factory respectively. Again, you'll need to save references to these in your initial module config.

UDPATE 2: 这里有一个小提琴自动注册不加载所有的控制器/指令/服务不必单独指定。

UDPATE 2: Here's a fiddle which automatically registers all controllers/directives/services loaded without having to specify them individually.

这篇关于动态加载AngularJS控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆