在angularjs有任何可用的功能,只允许数字被输入到一个文本框状
Answer 1:
该功能正是你需要的。 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();
}
}
});
Answer 2:
这段代码演示了如何防止进入非数字符号的例子。
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;
});
}
};
});
Answer 3:
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);
}
};
});
Answer 4:
我只是用NG-按键在指示我的输入。
HTML:
<input type="text" ng-keypress="filterValue($event)"/>
JS:
$scope.filterValue = function($event){
if(isNaN(String.fromCharCode($event.keyCode))){
$event.preventDefault();
}
};
Answer 5:
这是最简单和最快的方式,只允许输入的号码。
<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>
谢谢
Answer 6:
要建立在安东的回答一点 -
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;
});
}
};
});
Answer 7:
我的解决办法接受复制和粘贴,保存插入符的位置。 它用于产品的成本,从而只允许正十进制值。 可重构很容易让消极或只是整数位。
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" />
Answer 8:
基于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">
Answer 9:
这是对我工作的方法。 它的总部设在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();
};
Answer 10:
只需使用HTML5
<input type="number" min="0"/>
Answer 11:
您可以检查https://github.com/rajesh38/ng-only-number
- 它限制输入只有数字和小数点在文本框中打字时。
- 您可以限制之前,小数点后允许的位数
- 如果小数点从文本框中删除例如,如果你已经把123.45,然后去掉小数点它也将删除尾随数字小数点后并使其123也修剪小数点后面的数字。
Answer 12:
你可以做这样的事情:使用NG模式与正则表达式“/ ^ [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>
Answer 13:
该解决方案将只接受数字,“” 和“ - ”
这也限制了对文本框的空间入口。 我曾使用过的指令来实现相同的。
请对下面工作示例的解决方案。
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();
}
});
}
};
});
Answer 14:
这是简单易懂。 只要复制粘贴此代码,你的问题将得到resolved.For多个条件,只是改变了值pattern.and你的工作将会完成。
<input type="text" pattern="[0-9]{0,}" oninvalid="this.setCustomValidity('Please enter only numeric value. Special character are not allowed.')" oninput="setCustomValidity('')">
Answer 15:
我有一个类似的问题,最终挂钩和事件
ng-change="changeCount()"
然后:
self.changeCount = function () {
if (!self.info.itemcount) {
self.info.itemcount = 1;
}
};
因此,如果一个无效的数字插入用户默认为1。
Answer 16:
我arraged了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();
}
});
}
};
})
Answer 17:
<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();
}
Answer 18:
我知道这是一个老的文章,但我迈的回答的这种适应性很好地工作对我来说...
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);
}
};
});
Answer 19:
我在做
.js文件
$scope.numberOnly="(^[0-9]+$)";
html的
<input type="text" name="rollNo" ng-model="stud.rollNo" ng-pattern="numberOnly" ng-maxlength="10" maxlength="10" md-maxlength="10" ng-required="true" >
Answer 20:
这个答案作为简化和优化了波尔多的答案 。
触发来自你对这样的每一个的keydown输入的功能:
<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(); }
}
如果您正在使用角2+,你可以调用以这种方式这个相同的功能:
<input type="text" (keydown)="onlyNumbers($event);"/>
你的角2+功能应该是这个样子:
onlyNumbers(event) { // the logic here }
Answer 21:
<input type="phone" numbers-only >
如果你想只有数字,您可以用这种方式:)
这里是演示点击
Answer 22:
使用ng-only-number
只允许数字,例如:
<input type="text" ng-only-number data-max-length=5>
Answer 23:
<input
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 0 || event.charCode == 46">