javascript - 使用 Angular Directive(指令)在输入(类型=数字)中用逗号替换键盘句点

标签 javascript angularjs replace angularjs-directive numeric-input

问题:

最近有人要求我在使用 Angular 构建的 Spa 应用程序的字段中插入数字时,将键盘句点替换为逗号。 我决定采用指令方法,以便将来能够轻松地重用它,并取得了部分成功,但它仅适用于

input type="text"

上尝试相同的解决方案时
input type="number"

该字段被重置,我收到以下错误:

ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js:3501 The specified value "12," is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

但是当我输入 12 时,不会出现错误。

知道为什么以及如何让它在数字输入上工作吗?

代码:

'use strict';

myApp.directive('replaceKeypadComma', function() {
    return {
        restrict: 'A',
        link: function($scope, element, attrs, controller) {
            element.on('keydown', function(event) {
                if (event.keyCode == 110) {
                    element.val(element.val() + ',');
                    event.preventDefault();
                }
            });
        }
    }
});

使用文本输入操作 Plunker:

https://plnkr.co/edit/hBThZOI1T4rk3cbwRscq

带有数字输入的损坏的 Plunker:

https://plnkr.co/edit/zBqwWmZ0iAhIH728ZeCh

最佳答案

input type="number" 只允许包含“floating point number ”,因此 doesn't allow commas .

Some browsers接受包含小数逗号的输入并将其转换为小数点,具体取决于用户或页面的区域设置,但足够多的人不这样做,因此最好避免 input type="number" 如果您需要支持小数逗号数字。

关于javascript - 使用 Angular Directive(指令)在输入(类型=数字)中用逗号替换键盘句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482280/

相关文章:

javascript - Lightbox2 不工作; "Uncaught SyntaxError: Invalid or Unexpected Token"

javascript - 在 Angular js 中将对象导出为 Excel 文件

javascript - 从 angularjs 获取图像名称并在 laravel Blade 中使用它?

javascript - 使用 window.opener.location 从安全 (https) 弹出窗口访问非安全 (http) 开启器

javascript - AngularJS $http.post 调用返回 502(坏网关)错误

javascript - 用户选择文本并按删除/退格键时不会触发字数统计的 AngularJS 指令

vb.net - 在vb.NET中替换文件中的 'bel'字符

shell - 如何在 vim 的一行中替换特定索引处的字符?

javascript - 用正则表达式替换选择索引属性

javascript - 图像元素的 `complete` 属性究竟是如何工作的?