Restrict number of decimals in html5 type=“number” input field (with Angularjs model)

后端 未结 4 2172
太阳男子
太阳男子 2021-02-13 04:18

Please find the fiddle http://jsfiddle.net/q2SgJ/5/

WANTS: {{val | number:2}} in \"input\"
4条回答
  •  甜味超标
    2021-02-13 04:47

    I expanded on the accepted answer to look at the step attribute when determining how many decimal places to limit.

    directive('forcePrecision', function () {
        return {
            restrict: 'A',
            scope: {
               step: '@'
            },
            link: function (scope, element, attrs) {
                if (!scope.step || scope.step == 'any') {
                   return;
                }
    
                var prec = 1;
                for (var i = scope.step; i != 1; i *= 10) {
                    prec *= 10;
                }
    
                element.on('keypress', function (e) {
                    var val = Number(element.val() + (e.charCode !== 0  ? String.fromCharCode(e.charCode) : ''));
    
                    if (val) {
                        var newVal = Math.floor(val * prec) / prec;
    
                        if (val != newVal) {
                            e.preventDefault();
                        }
                    }
                });
            }
        };
    });
    

提交回复
热议问题