问题:
最近有人要求我在使用 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:
最佳答案
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/