[英]AngularJS - Dependency injection in services, factories, filters etc
So I have some plugins and libraries I want to use in my angular app and (currently) I am simply referencing those functions/methods as they were intended in 99% of apps in a way that completely ignores dependency injection. 所以我想在我的角度应用程序中使用一些插件和库,并且(目前)我只是引用那些函数/方法,因为它们在99%的应用程序中打算完全忽略依赖注入。
I have (for example) the javascript library "MomentJS" which deals with formatting and validating dates and I have uses for it throughout my app in controllers, services and filters. 我有(例如)javascript库“MomentJS”,它处理格式化和验证日期,我在控制器,服务和过滤器的整个应用程序中使用它。 The way that I've learned (using AngularJS) is to create a service that references the function (and it's methods) and inject that service into my controllers, which works great.
我学习的方法(使用AngularJS)是创建一个引用该函数(及其方法)的服务,并将该服务注入我的控制器,这非常有效。
The problem is that I really need to reference this library in all different kinds of components from services to filters to controllers and everything else. 问题是我真的需要在所有不同类型的组件中引用这个库,从服务到过滤器到控制器和其他所有组件。 So, I guess my question is how do you do dependency injection in filters, services and everything else that isn't a controller?
所以,我想我的问题是你如何在过滤器,服务和其他不是控制器的东西中进行依赖注入?
Is this possible? 这可能吗? Is this even beneficial?
这甚至有益吗?
Any help would be greatly appreciated :) 任何帮助将不胜感激 :)
Yes you can use dependency injection for filters and directives 是的,您可以使用依赖注入过滤器和指令
Ex: 例如:
Filter: 过滤:
app.filter('<filter>', ['$http', function(http){
return function(data){
}
}]);
Directive: 指示:
app.directive('<directive>', ['$http', function(http){
return {
....
}
}]);
Service: 服务:
app.factory('<service>', ['$http', function(http) {
var shinyNewServiceInstance;
return shinyNewServiceInstance;
}]);
For the sake of completeness, here is a service example with injection: 为了完整起见,这是一个带注入的服务示例:
app.service('<service>', ['$http', function($http) {
this.foo = function() { ... }
}]);
While the already existing answers are correct and working, john papas angular style guide favors the use of the $inject
service in Y091 : 虽然已经存在的答案是正确和有效的,但john papas角度样式指南有利于在Y091中使用
$inject
服务:
Filter: 过滤:
app.filter('<filter', MyFilter);
MyFilter.$inject = ['$http'];
function MyFilter() {
return function(data) {
}
}
Directive: 指示:
app.directive('<directive>', MyDirective);
MyDirective.$inject = ['$http'];
function MyDirective() {
return {
...
}
}
Factory: 厂:
app.factory('<factory>', MyFactory);
MyFactory.$inject = ['$http'];
function MyFactory() {
var shinyNewServiceInstance;
return shinyNewServiceInstance;
}
Service: 服务:
app.service('<service>', MyService);
MyService.$inject = ['$http'];
function MyService() {
this.foo = foo;
function foo(){
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.