Inject dateFilter in a service in AngularJs

。_饼干妹妹 提交于 2019-12-03 22:04:15
Stewie

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!