每当按下逗号(,)作为十进制输入而不是文本时,我都需要在输入上写点(。)。我需要以某种方式来模拟Keypress或KeyDown编程。
我尝试了所有答案here,但没有一个起作用:
我为输入编写了以下指令代码:
app.directive('ngKommatopoint', function() {
return {
link : function($scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 188) {
element.trigger(
$.Event( 'keydown', { keyCode:190,which:190})
);
}
});
},
restrict: 'A'
}; });
此解决方案不起作用,因为它从不调用“ Dot”事件。知道为什么它不起作用吗?
答案 0 :(得分:2)
在ngModelController上使用解析器/格式化程序来拦截用户输入。
您的解决方案将跳过复制/粘贴,但解析器/格式化程序不会。
https://dzone.com/articles/parsers-and-formatters-custom
您可以处理模型的所有更改并根据需要进行解析
更新
这里是小提琴:https://jsfiddle.net/gudzdanil/un56mjez/2/
app.directive('nodot', function(){
return{
require:'ngModel',
link: function(scope, elem, attrs, ctrl){
ctrl.$parsers.unshift(replace);
function replace(val){
var newVal = val.replace(/,/g, '.');
ctrl.$viewValue = newVal;
ctrl.$render()
return newVal;
}
}
};
});