Last active
April 24, 2019 13:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kept getting NaN for maxlength. The following worked for me
maxlength = parseInt(attrs.inputMaxLength, 10);