How can I create a filter to fill zero with the zero in the angular?

5

I'm developing an application using Laravel and AngularJS . I've always found it difficult to format a number to fill in with zeros in Javascript, so I opted to use Laravel to bring me the number of the id field already formatted with the zero fill.

But now I would like to do AngularJS, since I realized that the components of it (or even the ones that are created) can be highly reused.

What is the step for me to create a function to format the values displayed in view by filling leading zeros in Angular?

Is there a function for this already or do I need to create one? How to proceed?

For example:

 <tr ng-repeat="u in usuarios">
      <td ng-bind="usuario.id|preencher_com_quatro_zeros_a_esquerda"></td>
      <td ng-bind="usuario.nome"></td>

 </tr>

In the example I need to preencher_com_quatro_zeros_a_esquerda return a number formatted with 4 leading zeros. How to do?

    
asked by anonymous 29.09.2016 / 15:08

3 answers

7

Alternative:

filter('numberFixedLen', function () {
    return function (n, len) {
        var num = parseInt(n, 10);
        len = parseInt(len, 10);
        return (isNaN(num) || isNaN(len)) ? n : ( 1e10 + "" + num ).slice(-len);
    };
});
  • 1e10 means 10000000000, which is "summed" as a string in the original number, and then "cut" by the slice.

  • For numbers with more than 10 digits, needs to be adapted to 1e10

Source: link

Possible improvement: change 1e10 by Math.pow( 10, len )

It has been adapted and improved with more digits and verification.


Edit by comment:

Because it is a function normally used for fixed houses, it will cut numbers with more than 10 digits. If it is not the desired behavior, you need an adjustment. Here is a sample change:

return (isNaN(num) || isNaN(len) || (""+num).length>len) ? n : (1e10 + "" + num).slice(-len);
// Acrescente isso               ^^^^^^^^^^^^^^^^^^^^^^   
    
29.09.2016 / 15:27
7

Implementation as Filter:

.filter('numberFixedLen', function () {
    return function (n, len) {
        var num = parseInt(n, 10);
        len = parseInt(len, 10);
        if (isNaN(num) || isNaN(len)) {
            return n;
        }
        num = ''+num;
        while (num.length < len) {
            num = '0'+num;
        }
        return num;
    };
});

Usage:

{{meuValor | numberFixedLen:4}}

#

29.09.2016 / 15:13
4

Another option

.filter('numberFixedLen' function () {
    return function (a, b) {
        return (1e4 + a + "").slice(-b)
    }
});

Usage:

{{ valor | numberFixedLen:4 }}
    
29.09.2016 / 15:26