Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$parsers not working with space

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

like image 436
Eduardo in Norway Avatar asked Nov 27 '14 16:11

Eduardo in Norway


1 Answers

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, "");
like image 85
Rahil Wazir Avatar answered Nov 11 '22 14:11

Rahil Wazir