I want to set the html input[number] <input type="number" />
to allow only integer input (not float).
Basically, the html input[number] allow '.' to be entered for float input and I don't want that.
Is there a quick way to accomplish it in AngularJS?
Please find the fiddle http://jsfiddle.net/8a4sg0mo/
angular.module('myApp', []).directive('numbersOnly', function(){
return {
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;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
It will allow only numbers to be entered, purely done using angular js.
Here is how this can be achieved.
With input type - 'text'
Directive:
app.directive('onlyNumbers', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if(event.shiftKey){event.preventDefault(); return false;}
//console.log(event.which);
if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// backspace, enter, escape, arrows
return true;
} else if (event.which >= 48 && event.which <= 57) {
// numbers 0 to 9
return true;
} else if (event.which >= 96 && event.which <= 105) {
// numpad number
return true;
}
// else if ([110, 190].indexOf(event.which) > -1) {
// // dot and numpad dot
// return true;
// }
else {
event.preventDefault();
return false;
}
});
}
}
});
HTML:
<input type="text" only-numbers>
With input type - 'number'
Directive:
app.directive('noFloat', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if ([110, 190].indexOf(event.which) > -1) {
// dot and numpad dot
event.preventDefault();
return false;
}
else{
return true;
}
});
}
}
});
HTML:
<input type="number" step="1" no-float>
Check out the Plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With