I have a costume directive to set% of things, for example: - Happy: [90] - Sad: [10]
Thus, it can only allow from 1 to 100. Therefore, I do not want to allow any characters, etc. And I know that I can use ng-pattern, etc., but I do not want them to even add a character, so I need to do this.
This works, but the problem I have is that the space does not start $ parsers, is there a workaround to start it with the space as well?
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
angularjs parsing
Eduardo in norway
source share