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

Question:

Well I have a date 19102015, if I do it like this

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

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

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

00.000.000/0000-00

Can anyone tell me how I create specific formations with angularjs?

Thanks

Answer:

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 into lowercase when 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 processed by AngularJS:

<p>MINHA STRING</p>

See more about creating filters in the AngularJS documentation:

Developer Guide: Filters

Creating the CNPJ filter is an exercise!

Scroll to Top
AllEscort