Tuesday, January 3, 2017

TypeScripting AngularJS 1.x - Filters

This post is part of TypeScripting AngularJS 1.x series. Other posts are listed below. The sample code is created using Angular 1.5.9, TypeScript 1.8 & angularjs.TypeScript.DefinitelyTyped 6.5.6. 
  1. TypeScripting AngularJS 1.x - Define module
  2. TypeScripting AngularJS 1.x - Define module - improvements for big enterprise apps Improvement
  3. TypeScripting AngularJS 1.x - Using $http 
  4. TypeScripting AngularJS 1.x - Directives
  5. TypeScripting AngularJS 1.x - Filters

Angular Filters in TypeScript

These are small handy reusable functions which can help us to format the data while displaying without modifying the underlying model. Currency and date formatting are excellent examples. We don't need to keep one more property in the model which holds short date of another date object just for displaying. There are many filters built into Angular and it allows us to create new as well.

Below is a code snippet to create custom Angular filter named. HTMLTagRemover using TypeScript. As the name implies it removes any html tags in the string passed to it. 

export class HTMLTagRemover {
    public static filter(): Function {
        return (text: string): string => { 
            return text ? String(text).replace(/<[^>]+>/gm, '') : '' };
AppModule.getInstance().registerFilter("removeTags", HTMLTagRemover.filter);
It is a simple factory function which returns the actual filter function. The last line registers the filter with Angular application. It requires some prior knowledge related to defining Angular module in TypeScript way to understand how to get the AppModule.getInstance() and how it works.

Below is the code of registerFilter() in the AppModule class
registerFilter(name: string,fun:Function) {
    this.app.filter(name, fun);
The app is the real Angular object

Dependency injection 

Without dependency injection Angular is never complete. How can we get the dependencies injected into this filter?
export class HTMLTagRemover {
    static $inject: string[] = ['$sce'];
    public static filter($sce: ng.ISCEService): Function {
        return (text: string): string => {
            return text ? String(text).replace(/<[^>]+>/gm, '') : ''
This injects $sce which can be used to sanitize data into our filter. Similar to $sce we can inject our own services too.

Complete code can be found in my personal web site source in Github.

No comments: