AngularJS – Filter to add Leading 0s to any Number

Lets say you want to display a list of numbers from 1 to n but want them to be displayed as 01 02 03 04 05… and not 1 2 3 4 5… Angular by default doesn’t have a filter for this.

Here is how you implement it:

Implement the filter in a module. Here we take the variable len to define how many 0s must be prepended to the number.
If len is 2 then 1 becomes 01
If len is 3 then 1 becomes 001
If len is 4 then 1 becomes 0001… so on and so forth

angular.module('myModule', [])
.filter('fixedLengthPrefix', 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; }; });

Now add the filter to the markup:

{{number | fixedLengthPrefix:2}}