I have a costume directive to set % of things, for example: - Happy: [ 90 ] - Sad: [ 10 ]
So it can only allow 1 to 100. So I dont want to allow any characters etc.. And I know I can use ng-pattern etc.. but I don´t want them to even add a character so this I have to do.
It works, but the issue I have is that space does not trigger $parsers, is there a workaround for triggering it with space also?
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
//Remove all non numeric values
var transformedInput = inputValue.replace(/\D/g,'');
//Remove all spaces
transformedInput = transformedInput.replace(/\s/g, "");
//Remove any leading zero
if(transformedInput.substring(0,1) === '0') {
console.log('is zero');
if(transformedInput.length === 1) {
transformedInput = '';
} else {
transformedInput = transformedInput.substring(1, transformedInput.length);
}
}
//Make sure it is not over 100
var numberCopy = parseInt(transformedInput);
if(!isNaN(numberCopy)){
if(numberCopy > 100) {
console.log('bigger than 100');
numberCopy = 100;
transformedInput = String(numberCopy);
}
}
//If changes done, then update modelCtrl
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//Return
return transformedInput;
});
}
};
});
Plunker: http://plnkr.co/edit/oKXExZ8lkHzUSqHKpm1n?p=preview
Angular by default trim the ngModel
value. So you need to add ng-trim
directive to your input element, it doesn't allow spaces on both sides of the string.
<input type="text" numeric-only="" ng-trim="false" ng-model="nyNumber"/>
And you don't need this line anymore
//Remove all spaces
transformedInput = transformedInput.replace(/\s/g, "");
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