angularjs: allows only numbers to be typed into a text box

Ali Hasan picture Ali Hasan · Apr 18, 2013 · Viewed 207.2k times · Source

In angularjs is there any functionality available that allows only numbers to be typed into a text box like

Answer

Anton picture Anton · Oct 30, 2013

This code shows the example how to prevent entering non digit symbols.

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

    return {
        restrict: 'A',
        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;
            });
        }
    };
});