Skip to content

Instantly share code, notes, and snippets.

@aaronranard
Last active April 24, 2019 13:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronranard/e49ee4ea4b4f8cbacf17 to your computer and use it in GitHub Desktop.
Save aaronranard/e49ee4ea4b4f8cbacf17 to your computer and use it in GitHub Desktop.
Angular: directive to limit an input field to a max number of characters
app.directive('inputMaxlength', function() {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
var maxlength = Number(attrs.inputMaxlength);
function fromUser(text) {
if (text.length > maxlength) {
var transformedInput = text.substring(0, maxlength);
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
return transformedInput;
}
return text;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
@monetteContensive
Copy link

Kept getting NaN for maxlength. The following worked for me

maxlength = parseInt(attrs.inputMaxLength, 10);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment