0

I have an input box on my html page with gets databound to an ng-model. I use a directive to restrict the input field to numbers only. I cannot used the default HTML5 restrictions like type="number". The problem I have is that if a non digit char is entered twice, e.g to press 123 and then two times k, the k is added to 123 resulting in 123k. However when I press another key, the k gets removed by the directive.

Can someone help me out to fix the problem that the letter appears if you press the same key twice

The directive I use:

angular.module('app').
directive('onlyDigits', function () {

return {
    restrict: 'A',
    require: '?ngModel',
    link: function (scope, element, attrs, ngModel) {
        if (!ngModel) return;
        ngModel.$parsers.unshift(function (inputValue) {
            var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' '); }).join('');
            ngModel.$viewValue = digits;
            ngModel.$render();
            return digits;
        });
    }
};

});

1
  • 1
    Use var digits = inputValue.replace(/[^\d]/g, ''); instead of filter to remove non integers. Commented Sep 7, 2015 at 20:02

1 Answer 1

1

This is what we use to achieve numbers only in a directive:

directives.directive('numbersOnly', function () {
    'use strict';
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue === undefined) {
                    return '';
                }
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
});
Sign up to request clarification or add additional context in comments.

Comments

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.