Wednesday, June 17, 2015

Angular directive that will only allow numeric input


Create an input that is of type text. The directive will take the value and parse int therefore turning it into a number.

<input type="text" numeric-input-only ng-model="test.Units" required />

Directive:

angular.module('directives').directive('numericInputOnly', [function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
             
                // When ng required is used
                // In such cases, when a letter is typed first, this parser will be called
                // again, and the 2nd time, the value will be undefined
                if (inputValue == undefined)
                {
                    return '';
                }
                 
                var transformedInput = inputValue.toString().replace(/[^0-9]/g, '');
                if (transformedInput != inputValue) {

                    modelCtrl.$setViewValue(parseInt(transformedInput));
                    modelCtrl.$render();
                }

                return parseInt(transformedInput);
            });
        }
    };
}]);


Another example that I haven't tried yet is to prevent the user from being able to enter certain keys by binding to keydown.

.directive('onlyNum', function() {
        return function(scope, element, attrs) {

            var keyCode = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
            element.bind("keydown", function(event) {
                console.log($.inArray(event.which,keyCode));
                if($.inArray(event.which,keyCode) == -1) {
                    scope.$apply(function(){
                        scope.$eval(attrs.onlyNum);
                        event.preventDefault();
                    });
                    event.preventDefault();
                }

            });
        };
    })

No comments:

Post a Comment