Angular Typescript - using a custom filter inside the controller

I have my own filter in my angular (typescript) application, as shown below:

namespace InterACT { export namespace Filters { export class ContractAppliedTo { public static onFilterApplied(contract: Interfaces.IReimbursementContract) { if (contract.services && contract.services.length > 0) { return _.map(contract.services, 'regNumber').join(', '); } else if (contract.operator) { return contract.operator.name; } return contract.scheme.abbreviation; } } } } angular .module('app.settlement') .filter('contractAppliedTo', () => { return InterACT.Filters.ContractAppliedTo.onFilterApplied; }); 

I can use this filter just fine in my markup, like other built-in filters:

 {{rule | contractAppliedTo}} 

Now I need to use this filter in the controller, and I'm afraid how to refer to it for use.

I already use angular date filters in some of my controllers, and in the constructor from them I inject into ng.IFilterService and assigning a private variable for use later.

 namespace InterACT { export namespace Controllers { export class MyController { public static $inject = ['$filter']; constructor( private $filter: ng.IFilterService ) { } public someFunction = () => { let dateFilter = this.$filter('date'), foo; foo = dateFilter('some-date-string', 'dM-Y'); } } } } 

When it comes to using my ContractAppliedTo filter, I cannot get the controller to recognize it for me, or I assume that I mean that the typescript compiler will not pick it up.

I was wondering if I can use the filter service to grab an instance of my new filter, for example:

 let contractAppliedTo = this.$filter('contractAppliedTo') 

But when I try to use it, I get a typescript error saying

 [ts] Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. 

I think I lack an interface to be able to use this filter in my controller.

Can anyone advise further?

thanks

+5
source share
1 answer

This problem is that the FilterService cannot find the call signature for your custom filter. I was able to work around the problem by importing a custom filter and using type assertion against using the $filter service.

 const contractAppliedTo: contractAppliedTo = (<contractAppliedTo>this.$filter('contractAppliedTo')); 
0
source

Source: https://habr.com/ru/post/1263956/


All Articles