我有一个jsbin --> https://jsbin.com/yipigicuve/edit?html,console,output
根据链接,我有以下代码
<input ng-keypress="Num($event)" type="number" step=".1" ng-pattern="/^[+-]?(?:\d+\.?\d*|\d*\.?\d+)[\r\n]*$|^$/" ng-model="dataip"></>
$scope.Num = function (event) {
var keys = {
'up': 38, 'right': 39, 'down': 40, 'left': 37,
'escape': 27, 'backspace': 8, 'tab': 9, 'enter': 13, 'del': 46,
'0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57, 'dash':189, 'subtract':109
};
for (var index in keys) {
if (!keys.hasOwnProperty(index)) continue;
if (event.charCode == keys[index] || event.keyCode == keys[index]) {
return; //default event
}
}
event.preventDefault();
};
用户输入字母,但这些字母不被接受。某些字母数字键可以被接受,如变量“keys”中所示
提供了某些模式,以便可以接受空值、小数点。
我的问题是......jsbin中的当前输入类型接受诸如“-2.34---45”或“3.4...345”之类的值
它应该只接受一次小数点和负号。即“3.5566”或“-23.33”
有人可以让我知道如何使用 ng-pattern 来实现我的条件吗?
最佳答案
您可以简化您的生活并使用已经完成的内容。
使用此指令:nksOnlyNumber .
您可以根据您的要求设置输入。
这是一个正在运行的代码片段:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
})
.directive('nksOnlyNumber', function() {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
var spiltArray = String(newValue).split("");
if (attrs.allowNegative == "false") {
if (spiltArray[0] == '-') {
newValue = newValue.replace("-", "");
ngModel.$setViewValue(newValue);
ngModel.$render();
}
}
if (attrs.allowDecimal == "false") {
newValue = parseInt(newValue);
ngModel.$setViewValue(newValue);
ngModel.$render();
}
if (attrs.allowDecimal != "false") {
if (attrs.decimalUpto) {
var n = String(newValue).split(".");
if (n[1]) {
var n2 = n[1].slice(0, attrs.decimalUpto);
newValue = [n[0], n2].join(".");
ngModel.$setViewValue(newValue);
ngModel.$render();
}
}
}
if (spiltArray.length === 0) return;
if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.')) return;
if (spiltArray.length === 2 && newValue === '-.') return;
/*Check it is number or not.*/
if (isNaN(newValue)) {
ngModel.$setViewValue(oldValue || '');
ngModel.$render();
}
});
}
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="form">
<input type="text" nks-only-number ng-model="dataip" decimal-upto="6" />
</form>
</body>
</html>
关于javascript - 输入类型数字的 ng-pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314709/