导入多个AngularJS模块的工厂 [英] Importing multiple AngularJS module's factories

查看:116
本文介绍了导入多个AngularJS模块的工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一种方式来导入我的AngularJS模块中定义到控制器的所有工厂,而不必一一列举。说我有一个文件名为 foo.js 包含:

I was wondering if there was a way to import all the factories I've defined in an AngularJS module into a controller without having to list them all. Say I have a file named foo.js containing:

angular.module("Foo", [])
.factory("Bar1", function() {...})
.factory("Bar2", function() {...})
.factory("Bar3", function() {...})
.factory("Bar4", function() {...});

现在,在我的 controller.js 文件我有:

Now, in my controller.js file I have:

angular.module("myApp.controllers", ["Foo"]).
controller("MainCtrl", ["Bar1", "Bar2", "Bar3", "Bar4", function(bar1, bar2, bar3, bar4) {
    //do stuff with the various bars
}]);

我只是想知道是否有控制器的任何优雅的方式,因为它已经导入模块,以查看其所有工厂(或供应商,或服务,或作为指令事实上)。

I was simply wondering if there's any elegant way for the controller, since it already imports the module Foo, to see all its factories (or providers, or services, or directives as a matter of fact).

推荐答案

是的,这是可能的。

您可以动态加载模块的考察它 _invokeQueue 字段(见 HTTP ://stackoverflow.com/a/19412176/646543 的),以便检索模块中定义的所有工厂/控制器/等的名称

You can dynamically load a module an examine its _invokeQueue field (see http://stackoverflow.com/a/19412176/646543) in order to retrieve the names of all the factories/controllers/etc defined in a module.

您可以再使用 $注射器服务,以实际检索工厂。

You can then use the $injector service to actually retrieve the factories.

要证明,我创建了一个快速验证的演示。您应该能够直接复制和粘贴 IntrospectModule 出厂到您的应用程序获取此功能。

To demonstrate, I've created a quick proof-of-demo. You should be able to directly copy-and-paste the IntrospectModule factory into your app to get this functionality.

// Creating some test services
angular.module('test-services', [])
    .factory('Bar1', function() {
        return { 'stuff': function() { return 'calling bar1' } };
    })
    .factory('Bar2', function() {
        return { 'stuff': function() { return 'calling bar2' } };
    });

angular.module('myapp', ['test-services'])
    .factory('IntrospectModule', function($injector) {
        // This factory will dynamically return all services/controllers/directives/etc
        // given the module name.

        return function (moduleName) {
            var out = {};
            angular.module(moduleName)._invokeQueue.forEach(function(item) {
                var name = item[2][0];
                out[name] = $injector.get(name);
            });
            return out;
        };
    })
    .controller('MainCtrl', function($scope, IntrospectModule) {
        // And now I'm using it
        var testServices = IntrospectModule('test-services');
        $scope.test = testServices.Bar1.stuff();
    });

下面是上述的工作 plnkr

另外,如果感觉太哈克,你可以尝试创建一个复合工厂:

Alternatively, if that feels too hacky, you could try creating a 'composite' factory:

angular.module("test-services", [])
    .factory("Bar1", function() {...})
    .factory("Bar2", function() {...})
    .factory("Bar3", function() {...})
    .factory("Bar4", function() {...})
    .factory("EveryBar", ["Bar1", "Bar2", "Bar3", "Bar4", 
        function(bar1, bar2, bar3, bar4) {
            return {
                'bar1': bar1, 
                'bar2': bar2,
                'bar3': bar3,
                'bar4': bar4
            };
        }]);

然后,你的控制器里面,做的:

Then, inside your controllers, do:

angular.module("myApp.controllers", ["test-services"]).
controller("MainCtrl", ["EveryBar", function(everyBar) {
    everyBar.bar1.stuff();
}]);

显然,这种方法的缺点是它建立在你的服务会导致一个很好的协议冗余 - 我们还在手工列出一切

Obviously, the disadvantage of this approach is that it results in a good deal of redundancy when setting up your services -- we're still manually listing everything.

然而,如果你需要多次使用相同的服务,在几个不同的控制器,然后创建组合服务将至少可以让你不必列出一堆参数每个控制器。

However, if you need to use the same services multiple times in several different controllers, then creating the composite service would at least allow you avoid having to list a bunch of parameters in every controller.

它也更为明确,那么第一个解决方案,而且可以彻底枚举正是你想要而不是在角的内部出渣围绕服务,并让您扩展服务,添加辅助/包装的功能等。

It's also much more explicit then the first solution, and allows you to cleanly enumerate exactly which services you want rather then mucking around in the internals of Angular, and lets you extend the services, add helper/wrapper functions, etc.

这篇关于导入多个AngularJS模块的工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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