1

I have a input type= number field.It allows whole number and decimal number.But I need only whole number to be enter in the input.I have created a directive which is working only for input type=text,not working for input type=number.The reason is I need a number keyboard in mobile.

Below code is for number only,

Angularjs :

.directive('numbersOnly', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
        function fromUser(text) {
            if (text) {
                var transformedInput = text.replace(/[^0-9-]/g, '');
                if (transformedInput !== text) {
                    ngModelCtrl.$setViewValue(transformedInput);
                    ngModelCtrl.$render();
                }
                return transformedInput;
            }
            return '';
        }
        ngModelCtrl.$parsers.push(fromUser);
    }
};
})

Html:

  <input type="number" ng-model="points" numbers-only  required>

Any suggestions welcome

1 Answer 1

1

Try this

html

<input type="text"  ng-model="myText" name="inputName" numbers-only>

directive

myApp.directive('numbersOnly', function(){
     return {
         require: 'ngModel',
         link: function(scope, element, attrs, modelCtrl) {
             modelCtrl.$parsers.push(function (inputValue) {
                 var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'').replace('.','') : null;

                 if (transformedInput != inputValue) {
                   modelCtrl.$setViewValue(transformedInput);
                   modelCtrl.$render();
                 }

                 return transformedInput;
             });
          }
      };
});

https://jsfiddle.net/vorant/Lzw0yoma/

Sign up to request clarification or add additional context in comments.

2 Comments

this still doesn't solve the root question, which is using type="number".
thanks for the reply.but I need the solutions for input type="number".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.