How can I use an AngularJS filter to format a number to have leading zeros?

后端 未结 12 1766
挽巷
挽巷 2020-12-01 07:27

I checked the documentation. What I would like is for my numbers to have four digits and leading zeros.

22 to 0022
1  to 0001

Can someone

12条回答
  •  感动是毒
    2020-12-01 07:55

    Minimum code with underscore.string's padding function and the angular-underscore-string filter:

    working demo in jsFiddle


    angular string input -> angular-underscore-string filter -> underscore.string

    {{ num | s: 'pad':[4, '0'] }}
    angular.module('app', ['underscore.string']).controller('PadController', function ($scope) {
        $scope.nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    });
    
    // 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
    

    The s variable refers to the string library. In older versions you might have to substitute it for "_.str", ie. {{ num | _.str: 'pad':[4, '0'] }}

提交回复
热议问题