简体   繁体   English

Angular Dependency Injection,如果将控制器,服务等分离到单独的模块中

[英]Angular Dependency Injection if separating controllers, services, etc into separate modules

so I have my main module as such : 所以我的主要模块是这样的:

var app =  angular.module('LookupTool', ['ngRoute','controllers','services']);

and then my services in a seperate services.js file 然后将我的服务放在单独的services.js文件中

var services = angular.module('services',[]);

services.factory('WebServices',function(){
...
});

and then my controllers in a separate controller.js file 然后将我的控制器放在单独的controller.js文件中

var mainControllers = angular.module('controllers',[]);

mainControllers.controller('SearchCtrl', function ($scope) {

});

Now my question is with this level of modularity how do I inject my services into my controller, and is this a best practice set up? 现在,我的问题是在这种模块化水平上,如何将服务注入控制器中,这是最佳实践吗?

var mainControllers = angular.module('controllers',['services']);

mainControllers.controller('SearchCtrl', function ($scope,WebServices) {

});

I don't think it is right to setup in this way,modules should be business module and each module should contain its own controllers,services etc. 我认为以这种方式设置是不正确的,模块应该是业务模块,每个模块应该包含自己的控制器,服务等。

For example,for a university domain module can be like attendance,examination,reports etc. 例如,大学领域的模块可以像出勤,考试,报告等。

You can use it in following way provided your service is as follows 您可以按照以下方式使用它,前提是您的服务如下

    services.factory('WebServices',function(){
    var webService= new WebService();
    return webService;
    ...
    });

and have a function like 并具有类似

function WebServices(required angular variables)
{
..
}

.. add some prototype functions if required.. ..如果需要,添加一些原型功能。

. This will be your actual service. 这将是您的实际服务。

After that you can access it in following way 之后,您可以通过以下方式访问它

mainControllers.controller('SearchCtrl', function ($scope, webServices) {
$scope.webService= webService
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM