在 Angularjs 中格式化输入值 [英] Format input value in Angularjs

查看:33
本文介绍了在 Angularjs 中格式化输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个指令来自动格式化 <input> 中的数字,但模型没有格式化.让它工作很好,加载时输入中的值在控制器中显示为 1,000,000 和 1000000,但是当只输入 ngModel.$parsers 函数时会触发.ngModel.$formatters 触发的唯一时间是指令被加载并且值为 0 时.

I'm trying to write a directive that automatically formats a number in the <input> but the the model isn't formatted. Getting it to work is fine, on load the value in the input is displayed as 1,000,000 and 1000000 in the controller, however when typing only the ngModel.$parsers function fires. The only time when the ngModel.$formatters fire is when the directive gets loaded and when the value is 0.

我怎样才能让它在 keypress 上工作(我已经尝试绑定到 keypress/keyup 但它不起作用).

How can I make it work on keypress(I've tried binding to keypress/keyup but it doesn't work).

这是我的代码:

angular.module('myApp.directives', []).directive('filterInput', ['$filter', function($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            ngModel.$parsers.push(function fromUser(text) {
                return parseInt(text.replace(",", ""));
            });

            ngModel.$formatters.push(function toUser(text) {
                console.log($filter('number')(text));
                return ($filter('number')(text || ''));
            });

        }
    };
}]);

推荐答案

这是我们使用 unshift 的工作示例:

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;
            });
        }
    };
}]);

HTML 似乎:

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

查看演示 Fiddle

希望对您有所帮助

这篇关于在 Angularjs 中格式化输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆