AngularJS - 依赖注入服务,工厂,过滤器等 [英] AngularJS - Dependency injection in services, factories, filters etc
问题描述
所以我有一些插件和库我想在我的角度应用程序,并使用(目前)我只是引用这些函数/方法,因为他们打算在完全忽略了依赖注入的方式应用的99%。
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.
我有(例如)JavaScript库MomentJS,这与格式和验证日期,交易和我有它的用途在我的控制器,服务和过滤器应用程序。我已经学会(使用AngularJS)的方法是创建引用功能的服务(和它的方法),并注入该服务进入我的控制器,它的伟大工程。
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. 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.
问题是,我真的需要从服务于各种不同类型的组件来引用这个库过滤器,控制器和其他一切。所以,我想我的问题是你如何在过滤器,服务和其他所有依赖注入,是不是控制器?
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?
任何帮助将大大AP preciated:)
Any help would be greatly appreciated :)
推荐答案
是的,你可以使用依赖注入过滤器和指令
Yes you can use dependency injection for filters and directives
例如:
过滤器:
app.filter('<filter>', ['$http', function(http){
return function(data){
}
}]);
指令:
app.directive('<directive>', ['$http', function(http){
return {
....
}
}]);
服务:
app.factory('<service>', ['$http', function(http) {
var shinyNewServiceInstance;
return shinyNewServiceInstance;
}]);
这篇关于AngularJS - 依赖注入服务,工厂,过滤器等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!