AngularJS Input Max Length Directive

Mon, 05 Jan 2015

In case you need to set a max length to a model binded input, well check this directive:

'use strict';

angular .module('APP') .directive('uiMaxlength', function() { return { require: 'ngModel', link: function(scope, el, attrs, model) { var max_length = parseInt(attrs.uiMaxlength, 10);

        var input\_value\_parser = function(value) {
            if(value.length > max\_length) {
                value = value.substring(0, max\_length);
                model.$setViewValue(value);
                model.$render();
            }

            return value;
        };

        model.$parsers.push(input\_value\_parser);
    }
};

})

;

Usage:

<input ui-maxlength="10" type="text" name="input_name" ng-model="model_name" />

With some minor changes this directive can also be used for setting Min Length.

Categories: angularjs, javascript