Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom Angular filter with TypeScript

I'm trying to work out the best way of creating a custom Angular Filter with TypeScript.

All the code samples I see use something like:

myModule.filter( "myFilter", function()
{
    return function( input )
    {
        //  filter stuff here
        return result;
    }
}

... which works, but seems messy as I want to keep all my filter code separate. So I want to know how to declare the filter as a separate file (eg filters/reverse-filter.ts) so I can create it like:

myModule.filter( "filterName", moduleName.myFilter );

... the same way you would for Controllers, Services etc.

The documentation for TS and Angular together seems pretty thin on the ground, especially where filters are concerned - can anyone help out?

Cheers!

like image 419
Tom Evans Avatar asked Aug 04 '14 13:08

Tom Evans


2 Answers

Functions can be exported from modules like this:

module moduleName {
    export function myFilter()
    {
        return function(input)
        {
            //  filter stuff here
            return result;
        }
    }
}

then outside the module:

myModule.filter("filterName", moduleName.myFilter);

Then it would then be possible to do things like automatically register all of the filters defined in the moduleName module by iterating over its public properties.

like image 150
Douglas Avatar answered Sep 18 '22 22:09

Douglas


Maybe too late but can be useful for someone else.

module dashboard.filters{

    export class TrustResource{

        static $inject:string[] = ['$sce'];

        static filter($sce:ng.ISCEService){

            return (value)=> {
                return $sce.trustAsResourceUrl(value)
            };
        }
    }
}     
    dashboard.Bootstrap.angular.filter('trustAsResourceUrl',dashboard.filters.TrustResource.filter);

To explain the last line:

dashboard.Bootstrap.angular.filter('trustAsResourceUrl',dashboard.filters.TrustResource.filter);)

I will add a piece of code, wich represents my Bootstrap class, so you can understand it.

module dashboard {
    export class Bootstrap {

        static angular:ng.IModule;

        static start(){        
            Bootstrap.angular = angular.module('EmbApp', dashboard.Bootstrap.$inject);
        }


    }
}

//run application
dashboard.Bootstrap.start();

If you need more information about how it works, you can checkout my own TypeScript/AngularJS/Less structure here

like image 24
Dazag Avatar answered Sep 21 '22 22:09

Dazag