在angularjs中,有任何可用的功能,仅允许将数字键入文本框中,例如
在angularjs中,有任何可用的功能,仅允许将数字键入文本框中,例如
Answers:
此功能正是您所需要的。http://docs.angularjs.org/api/ng.directive:input.number
编辑:
您可以将jquery插件包装到指令中。我在这里创建了一个示例:http : //jsfiddle.net/anazimok/jTJCF/
HTML:
<div ng-app="myApp">
<div>
<input type="text" min="0" max="99" number-mask="" ng-model="message">
<button ng-click="handleClick()">Broadcast</button>
</div>
</div>
CSS:
.ng-invalid {
border: 1px solid red;
}
JS:
// declare a module
var app = angular.module('myApp', []);
app.directive('numberMask', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).numeric();
}
}
});
此代码显示了如何防止输入非数字符号的示例。
angular.module('app').
directive('onlyDigits', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
attrs.$set('ngTrim', "false");
在解析器前添加以防止出现空格。
的HTML
<input type="text" name="number" only-digits>
//只需输入123
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
//输入:123或123.45
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
我只是在指令中使用ng-keypress输入。
HTML:
<input type="text" ng-keypress="filterValue($event)"/>
JS:
$scope.filterValue = function($event){
if(isNaN(String.fromCharCode($event.keyCode))){
$event.preventDefault();
}
};
这是最简单,最快的方法,仅允许输入数字。
<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>
谢谢
为了进一步了解安东的答案-
angular.module("app").directive("onlyDigits", function ()
{
return {
restrict: 'EA',
require: '?ngModel',
scope:{
allowDecimal: '@',
allowNegative: '@',
minNum: '@',
maxNum: '@'
},
link: function (scope, element, attrs, ngModel)
{
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue)
{
var decimalFound = false;
var digits = inputValue.split('').filter(function (s,i)
{
var b = (!isNaN(s) && s != ' ');
if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
{
if (s == "." && decimalFound == false)
{
decimalFound = true;
b = true;
}
}
if (!b && attrs.allowNegative && attrs.allowNegative == "true")
{
b = (s == '-' && i == 0);
}
return b;
}).join('');
if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
{
digits = attrs.maxNum;
}
if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
{
digits = attrs.minNum;
}
ngModel.$viewValue = digits;
ngModel.$render();
return digits;
});
}
};
});
ngModel.$viewValue = digits
您应该使用ngModel.$setViewValue(digits)
ngModelController和ngForm钩子的其余部分,而不是使用它。我需要它,因为这是必填字段,当我输入字母(未显示)时,表格被标记为有效-错误。
我的解决方案接受“复制粘贴”并保存插入符号的位置。它用于产品成本,因此仅允许使用正十进制值。可以很容易地重构,以允许负数或整数。
angular
.module("client")
.directive("onlyNumber", function () {
return {
restrict: "A",
link: function (scope, element, attr) {
element.bind('input', function () {
var position = this.selectionStart - 1;
//remove all but number and .
var fixed = this.value.replace(/[^0-9\.]/g, '');
if (fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if (pos >= 0) //avoid more than one .
fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
}
};
});
放在html页面上:
<input type="text" class="form-control" only-number ng-model="vm.cost" />
这是对我有效的方法。它的总部设在samnau anwser但允许提交与形式ENTER
,增加和减少与数字UP
和DOWN
箭头用,编辑DEL
,BACKSPACE
,LEFT
和RIGHT
,然后导航槽与领域TAB
。请注意,它适用于正整数,例如金额。
HTML:
<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >
ANGULARJS:
$scope.onlyNumbers = 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
};
for(var index in keys) {
if (!keys.hasOwnProperty(index)) continue;
if (event.charCode==keys[index]||event.keyCode==keys[index]) {
return; //default event
}
}
event.preventDefault();
};
基于djsiz解决方案,包装在指令中。注意:它不会处理数字,但可以轻松更新
angular
.module("app")
.directive("mwInputRestrict", [
function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.on("keypress", function (event) {
if (attrs.mwInputRestrict === "onlynumbers") {
// allow only digits to be entered, or backspace and delete keys to be pressed
return (event.charCode >= 48 && event.charCode <= 57) ||
(event.keyCode === 8 || event.keyCode === 46);
}
return true;
});
}
}
}
]);
的HTML
<input type="text"
class="form-control"
id="inputHeight"
name="inputHeight"
placeholder="Height"
mw-input-restrict="onlynumbers"
ng-model="ctbtVm.dto.height">
只需使用HTML5
<input type="number" min="0"/>
您可以检查 https://github.com/rajesh38/ng-only-number
您可以执行以下操作:将ng-pattern与RegExp“ / ^ [0-9] + $ / ”一起使用,这意味着仅整数有效。
<form novalidate name="form">
<input type="text" data-ng-model="age" id="age" name="age" ng-pattern="/^[0-9]+$/">
<span ng-show="form.age.$error.pattern">The value is not a valid integer</span>
</form>
该解决方案将仅接受数字“。”。和“-”
这也限制了文本框中的空格输入。我曾经使用该指令来实现相同的目的。
请在以下工作示例中找到解决方案。
http://jsfiddle.net/vfsHX/2697/
HTML:
<form ng-app="myapp" name="myform" novalidate>
<div ng-controller="Ctrl">
<input name="number" is-number ng-model="wks.number">
<span ng-show="!wks.validity">Value is invalid</span>
</div>
JS:
var $scope;
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope) {
$scope.wks = {number: 1, validity: true}
});
app.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind("keydown keypress", function (event) {
if(event.which === 32) {
event.returnValue = false;
return false;
}
});
scope.$watch(attrs.ngModel, function(newValue,oldValue) {
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue)) {
//scope.wks.number = oldValue;
ngModel.$setViewValue(oldValue);
ngModel.$render();
}
});
}
};
});
简单易懂。只需复制粘贴此代码即可解决您的问题。对于更多情况,只需更改pattern中的值即可完成工作。
<input type="text" pattern="[0-9]{0,}" oninvalid="this.setCustomValidity('Please enter only numeric value. Special character are not allowed.')" oninput="setCustomValidity('')">
我在这里加了jQuery
.directive('numbersCommaOnly', function(){
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.on('keydown', function(event) {
// Allow: backspace, delete, tab, escape, enter and .
var array2 = [46, 8, 9, 27, 13, 110, 190]
if (array2.indexOf(event.which) !== -1 ||
// Allow: Ctrl+A
(event.which == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+C
(event.which == 67 && event.ctrlKey === true) ||
// Allow: Ctrl+X
(event.which == 88 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.which >= 35 && event.which <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
event.preventDefault();
}
});
}
};
})
<input type="text" ng-keypress="checkNumeric($event)"/>
//inside controller
$scope.dot = false
$scope.checkNumeric = function($event){
if(String.fromCharCode($event.keyCode) == "." && !$scope.dot){
$scope.dot = true
}
else if( isNaN(String.fromCharCode($event.keyCode))){
$event.preventDefault();
}
我知道这是一篇过时的文章,但是对我的答案的改编对我来说非常有效...
angular.module("app").directive("numbersOnly", function() {
return {
require: "ngModel",
restrict: "A",
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
//transform val to a string so replace works
var myVal = val.toString();
//replace any non numeric characters with nothing
var digits = myVal.replace(/\D/g, "");
//if anything needs replacing - do it!
if (digits !== myVal) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
该答案是对Leopoldo答案的简化和优化。
在每次按下按键时从您的输入触发功能,如下所示:
<input type="text" ng-keydown="onlyNumbers($event);"/>
您可以在控制器中以这种方式描述功能
$scope.onlyNumbers = function(event){
// '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
var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
54:true,55:true,56:true,57:true };
// if the pressed key is not listed, do not perform any action
if(!keys[event.keyCode]) { event.preventDefault(); }
}
如果您使用的是Angular 2+,则可以通过以下方式调用此相同的函数:
<input type="text" (keydown)="onlyNumbers($event);"/>
您的Angular 2+函数应如下所示:
onlyNumbers(event) { // the logic here }
<input
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 0 || event.charCode == 46">