Patrick Patrick - 4 months ago 32
AngularJS Question

input type number + ng-keypress to allow '-' sign

I have the below input type number mentioned. Along with numbers, i want some other keyboard characters to be accepted. Hence i have used ng-pattern to accept "null", ".","+" and "-" values

It also have ng-keypress function where i have mentioned about ----> 'dash':189, 'subtract':109. These are keyboard codes to accept '-' from keyboard.

Somehow it is not accepting '-'. I tried to put various patterns so that '-' is accepted. But it doesnt.

<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();
};


Can someone please have a look and advice...

Answer

Please look at this ASCII table: enter image description here Character code (Dec column) for - is 45.

Here is working JSBin: https://jsbin.com/yipigicuve/edit?html,console,output

BTW I think you don't need to set type="number" on input element. Please also consider inputs like --3---8438, currently you are accepting inputs like this. Please consider using some library like https://github.com/candreoliveira/ngMask.