Format input value in Angularjs

后端 未结 3 429
长发绾君心
长发绾君心 2020-11-30 23:38

I\'m trying to write a directive that automatically formats a number in the but the the model isn\'t formatted. Getting it to work is fine, on lo

相关标签:
3条回答
  • 2020-12-01 00:13

    Small edit to Maxim Shoustin's answer below as per the answer to this question: AngularJS formatter - how to display blank instead of zero

    Only change is to ensure that the input is blank rather than zero on the deletion of the last number:

       ctrl.$parsers.unshift(function (viewValue) {
            console.log(viewValue);
            if(viewValue){
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter('number')(plainNumber));
                return plainNumber;
            }else{
                return '';
            }
        });
    

    http://jsfiddle.net/2n73j6rb/

    0 讨论(0)
  • 2020-12-01 00:21

    This module works fine for me.

    https://github.com/assisrafael/angular-input-masks

    Example:

    <input type="text" name="field" ng-model="number" ui-number-mask>
    
    0 讨论(0)
  • 2020-12-01 00:24

    Here is working example where we use unshift:

    angular.module('myApp.directives', []).directive('format', ['$filter', function ($filter) {
        return {
            require: '?ngModel',
            link: function (scope, elem, attrs, ctrl) {
                if (!ctrl) return;
    
    
                ctrl.$formatters.unshift(function (a) {
                    return $filter(attrs.format)(ctrl.$modelValue)
                });
    
    
                ctrl.$parsers.unshift(function (viewValue) {
                    var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                    elem.val($filter(attrs.format)(plainNumber));
                    return plainNumber;
                });
            }
        };
    }]);
    

    The HTML seems:

    <input type="text" ng-model="test" format="number" />
    

    See Demo Fiddle

    Hope its help

    0 讨论(0)
提交回复
热议问题