gpt4 book ai didi

javascript - Angular 将输入限制为粘贴时的数字

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:25 26 4
gpt4 key购买 nike

我有这个指令在 <input type='text'> 中运行限制用户输入只能输入数字。工作正常!

我的问题是,如果用户复制/粘贴一些字符串,Angular 就会接受该值并将该字符串发送到后端。

angular.module('autonumeric', []).directive('ngNumeric', [function () {
'use strict';
// Declare a empty options object
var options = {};
return {
// Require ng-model in the element attribute for watching changes.
require: '?ngModel',
// This directive only works when used in element's attribute (e.g: cr-numeric)
restrict: 'A',
compile: function (tElm, tAttrs) {

var isTextInput = tElm.is('input:text');

return function (scope, elm, attrs, controller) {
// Get instance-specific options.
var opts = angular.extend({}, options, scope.$eval(attrs.crNumeric));

// Helper method to update autoNumeric with new value.
var updateElement = function (element, newVal) {
// Only set value if value is numeric
if ($.isNumeric(newVal))
element.autoNumeric('set', newVal);
};

// Initialize element as autoNumeric with options.
elm.autoNumeric(opts);

// if element has controller, wire it (only for <input type="text" />)
if (controller && isTextInput) {
// render element as autoNumeric
controller.$render = function () {
updateElement(elm, controller.$viewValue);
}
// watch for external changes to model and re-render element
scope.$watch(tAttrs.ngModel, function (current, old) {
//controller.$render();
updateElement(elm, controller.$viewValue);
});
// Detect changes on element and update model.
elm.on('change', function (e) {
scope.$apply(function () {
controller.$setViewValue(elm.autoNumeric('get'));
});
});
}
else {
// Listen for changes to value changes and re-render element.
// Useful when binding to a readonly input field.
if (isTextInput) {
attrs.$observe('value', function (val) {
updateElement(elm, val);
});
}
}
}
} // compile
} // return
}]);

我尝试使用正则表达式替换 replace(/[^0-9.]/g, '')删除所有字符,但不起作用。有人知道如何改进此指令,即使在复制/粘贴时也只接受数字吗?

最佳答案

我编写了一个类似的指令,它只允许 float (并且还将 , 转换为 .)。这是最简单的,所以我认为你可以使用它:

angular.module('myMod').directive('floatOnly', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if(inputValue === undefined) return '';

// Remove forbidden characters
cleanInputValue = inputValue.replace(',', '.') // change commas to dots
.replace(/[^\d.]/g, '') // keep numbers and dots
.replace(/\./, "x") // change the first dot in X
.replace(/\./g, "") // remove all dots
.replace(/x/, "."); // change X to dot
if(cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});

您可以按如下方式使用它:

<input type="text" ng-model="myFloat" float-only/>

Demo on JSFiddle

关于javascript - Angular 将输入限制为粘贴时的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com