在 AngularJs 的服务中注入 dateFilter [英] Inject dateFilter in a service in AngularJs
问题描述
我想知道是否有办法在 AngularJs 的服务中注入过滤器.
I would like to know if there is a way to inject the filters in a service in AngularJs.
我一直在努力
app.factory('educationService', [function($rootScope, $filter) {
// ..... Some code
// What I want
console.log(dateFilter(new Date(), 'yyyy-MM-01'));
// ..... Some code
}]);
所以我想知道是否可以在服务中注入过滤器,或者是否可以通过其他方式访问它.
So I would like to know if it is possible to inject a filter in a service or maybe it is accessible in another way.
如果你有一个关于这一点的文档的链接,那就太好了:) 一直在 Angular 的文档中搜索,我发现没有任何关于这点的真正有用的东西.
And if you have a link to a documentation about this point, it would be really nice :) Been searching in the doc of Angular and I found nothing really helpful about this.
谢谢:)
推荐答案
首先你必须像这样注入过滤器:
First you have to inject the filter like this:
app.factory('myService', ['$rootScope', '$filter', function($rootScope, $filter)
(只有在构建过程中使用缩小时才需要该数组)
(The array is only needed when you use minification in your build process)
以编程方式调用特定过滤器:
To call specific filter programmatically:
$filter('date')(new Date(), 'yyyy-MM-01');
$filter(name)
返回特定的过滤器函数,您可以使用参数调用该函数:
$filter(name)
returns the specific filter function, which you can than call with your arguments:
var dateFilter = $filter('date');
var filteredDate = dateFilter(new Date(), 'yyyy-MM-01')
这篇关于在 AngularJs 的服务中注入 dateFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!