How do I create a custom formatting in a string with angularjs?

2

Well I have a date 19102015, if I do so

{{step.data | date:'dd/MM/yyyy'}} 

I can format the date and get 10/19/2015.

But in my case I need something customized. I have a cnpj that comes like this: 00000000000000 and I need to format it like this

00.000.000/0000-00

Does anyone know how to create specific formations with angularjs?

Thank you

    
asked by anonymous 03.02.2015 / 19:26

1 answer

1

What you are looking for in AngularJS is called filter .

A filter takes an input value and optional configuration parameters, and returns a value that will actually be displayed in the interface.

A filter is created as follows:

angular.module('MeuModulo', []).filter('nomeDoFiltro', function() {
    return function(input, arg1, arg2) {
        var out;
        // manipula input e seus argumentos...
        return out;
    };
});

For example, a filter that transforms a string into uppercase when parameter is true , and in lowercase when the parameter is false :

angular.module('MeuModulo', []).filter('case', function() {
    return function(input, uppercase) {
        var out = "";
        if ( uppercase ) {
            out = input.toUpperCase();
        } else {
            out = input.toLowerCase();
        }
        return out;
    };
});

This filter can then be used in your HTML:

<p>{{ 'minha string' | case:true }}</p>

Echoing after rendered by AngularJS:

<p>MINHA STRING</p>

See more about creating filters in the AngularJS documentation:

Developer Guide: Filters

Creating the filter for the CNPJ stays as an exercise!

    
03.02.2015 / 21:24