简体   繁体   English

AngularJS,将服务注入控制器

[英]AngularJS, injecting service into controller

I just began to work with angularJS and started to divide my main.js into several own files. 我刚刚开始使用angularJS,并开始将main.js分成几个自己的文件。 My structure is as follows: 我的结构如下:

app.js app.js

index.html index.html

/service/service1 / service / service1

/controller/cont1 /控制器/ cont1

My question is how to inject the service into the controller. 我的问题是如何将服务注入控制器。

The App: 该应用程序:

angular.module('App',['ngDragDrop']);

The service: 服务:

angular.module('App')
   .factory('service1',function()
{...}

I tried to load the service1 into cont1 by injecting 我试图通过注入将service1加载到cont1中

angular.module('App')
    .controller('cont1', cont1);

cont1.$inject=['$scope', 'service1']; 

function cont1($scope, service1) {
    $scope.we=service1.doSomething(); 
}

but it never worked. 但它从来没有奏效。

Finally I added the script of service1 into my index.html file, just before I load the controller file and it worked fine. 最终,在加载控制器文件之前,我将service1脚本添加到了index.html文件中,并且该脚本运行良好。

Do I have to add every service I want to use somewhere in my app into the index file? 我是否必须将要在应用程序中某处使用的每项服务添加到索引文件中? Is there no other way? 有没有其他办法? To me it seems somehow dumb if I have tons of script tags in my index.html 对我来说,如果我的index.html中有大量脚本标签,那似乎有点愚蠢

Greetz and thanks in advance! Greetz,并预先感谢!

Yes, your index.html will contain all your scripts references. 是的,您的index.html将包含所有脚本引用。 You can get fancy and create a task that will minify and combine all your js file into one then only have only 1 file referenced. 您可以幻想并创建一个任务,该任务将最小化并将所有js文件合并为一个,然后仅引用1个文件。 For debugging purposes, you wanna have access to all your js files in case you want set breakpoints and debug 为了进行调试,您想访问所有js文件,以防设置断点和调试

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

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