Em angularjs existe alguma funcionalidade disponível que permite que apenas números sejam typescripts em uma checkbox de texto como
Esta funcionalidade apenas o que você precisa. http://docs.angularjs.org/api/ng.directive:input.number
EDITAR:
Você pode colocar o plugin jquery na diretiva. Eu criei um exemplo aqui: http://jsfiddle.net/anazimok/jTJCF/
HTML:
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(); } } });
Este código mostra o exemplo de como impedir a inserção de símbolos não dígitos.
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; }); } }; });
HTML
// Apenas digite 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); } }; });
// tipo: 123 ou 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); } }; });
Eu apenas usei ng-keypress na diretiva para minha input.
HTML:
JS:
$scope.filterValue = function($event){ if(isNaN(String.fromCharCode($event.keyCode))){ $event.preventDefault(); } };
Esta é a maneira mais simples e rápida de permitir a input do Número apenas.
obrigado
Para construir a resposta de Anton um pouco –
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; }); } }; });
Minha solução aceita Copy & Paste e salva a posição do cursor. É usado para o custo dos produtos, portanto, permite somente valores decimais positivos. Pode ser muito fácil refatorar para permitir dígitos inteiros negativos ou apenas inteiros.
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; } }); } }; });
Coloque na página html:
Baseado na solução djsiz , envolto em diretiva. NOTA: ele não irá lidar com números de dígitos, mas pode ser facilmente atualizado
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
Este é o método que funciona para mim. É baseado em samnau anwser, mas permite enviar o formulário com ENTER
, aumentar e diminuir o número com as setas DOWN
UP
e DOWN
, editar com DEL
, BACKSPACE
, LEFT
e RIGHT
, e navegar pelos campos com TAB
. Observe que ele funciona para inteiros positivos, como um valor.
HTML:
Basta usar HTML5
Você pode verificar https://github.com/rajesh38/ng-only-number
Você poderia fazer algo assim: Use ng-pattern com o RegExp ” / ^ [0-9] + $ / “, o que significa que apenas números inteiros são válidos.
Esta solução aceitará apenas um numérico, ‘.’ e ‘-‘
Além disso, isso restringe a input de espaço na checkbox de texto. Eu usei a diretiva para conseguir o mesmo.
Por favor, tenha a solução no exemplo de trabalho abaixo.
http://jsfiddle.net/vfsHX/2697/
HTML:
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(); } }); } }; });
É simples e compreensível. Basta copiar e colar esse código e seu problema será resolvido. Para mais condições, basta alterar o valor no padrão e seu trabalho será feito.
Eu tive um problema semelhante e acabei enganchando e evento
ng-change="changeCount()"
então:
self.changeCount = function () { if (!self.info.itemcount) { self.info.itemcount = 1; } };
Portanto, o usuário é padronizado como 1 se um número inválido for inserido.
Eu arraged o jQuery neste
.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(); } }); } }; })
//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(); }
Eu sei que este é um post antigo, mas esta adaptação da resposta do My Mai funciona bem para mim …
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); } }; });
Eu fiz em
.js
$scope.numberOnly="(^[0-9]+$)";
.html
Use ng-only-number
para permitir apenas números, por exemplo: