栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

动态加载AngularJS控制器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动态加载AngularJS控制器

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

// Make module Foo and store $controllerProvider in a globalvar controllerProvider = null;angular.module('Foo', [], function($controllerProvider) {    controllerProvider = $controllerProvider;});// Bootstrap Fooangular.bootstrap($('body'), ['Foo']);// .. time passes ..// Load javascript file with Ctrl controllerangular.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 configfunction 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
。同样,您需要在初始模块配置中保存对这些引用的引用。

UDPATE 2:
它会自动注册所有加载的控制器/指令/服务,而无需单独指定它们。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号