简体   繁体   中英

Inject dateFilter in a service in AngularJs

I would like to know if there is a way to inject the filters in a service in AngularJs.

I've been trying

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.

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.

Thanks :)

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) 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')

The filter function is registered with the $injector under the filter name suffixed with Filter . -- $filterProvider docs

This is true for the Angular built-in filters, as well as your own custom filters.

So, you can inject the dateFilter into your service like this (if not minifying):

app.factory('educationService', [function($rootScope, dateFilter) {

If you are only using one filter, this method allows you to be more specific about your actual dependencies. If you need to use multiple filters, you can inject $filter like @Stewie shows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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