1

Is it possible to output a fixed number of digits on a {{ expression }}.

For example say I have timer which is counting down >>> 10, 9, 8, 7, 6, ... 0.

Is it possible to filter this output so that the output is now >>> 10, 09, 08, 07, ... 00.

Thanks in Advance.

aozkan
  • 691
  • 1
  • 8
  • 17

2 Answers2

6

You can write your own filter. I took TimSPQR's comment and added to a Jsfiddle with a custom filter.

angular.module('MyModule', []).filter('digits', function() {
return function(input) {
   if (input < 10) { 
          input = '0' + input;
      }

      return input;
    }
});

Usage in html:

Add Leading Zero: {{number|digits}}

Jsfiddle

Keep in mind you will need to add logic to account for non-numbers and numbers that already start with a leading zero. This should give you the basic idea though.

-Cheers

Aaron Hickman
  • 837
  • 6
  • 16
  • 1
    Thanks that should do the trick! I wasn't sure if this functionality came out-of-the-box. – aozkan Jul 25 '13 at 04:58
  • 3
    Just felt like playing with this one, made it generic so you can have it pad with any number of 0s just by specifying a length after the digit filter as the expression: http://jsfiddle.net/CwUSe/3/ – shaunhusain Jul 25 '13 at 05:11
0

For supporting any length of input it better using the following filter (based on Pointy answer: Pad a number with leading zeros in JavaScript)

JS:

angular.module('MyModule', [])    
.filter('digits', function () {
            return function (input, width, leadingChar) {
                leadingChar = leadingChar || '0';
                input = input + '';
                return input.length >= width ? input : new Array(width - input.length + 1).join(leadingChar) + input;
            }
        });

HTML:

<span>{{(number | digits : 2}}</span>
Community
  • 1
  • 1
Dor Cohen
  • 15,873
  • 22
  • 85
  • 152