I've seen some examples in jQuery and JS about this.
I've been looking around and I can see that you can limit the length (see fiddle). I was wondering if there was a way to limit the number of rows or lines in AngularJS or if character length is the way to go?
<textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>
Thanks! T
Here is a working directive I came up with, using the new ngModel.$validators pipeline in the AngularJS 1.3 branch:
/*
maxlines attribute directive, specify on a <textarea> to validate the number
of lines entered is less than the specified value.
Optional attributes:
maxlines-prevent-enter: Specify as false to NOT block the pressing of the Enter
key once the max number of lines has been reached.
*/
app.directive('maxlines', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var maxLines = 1;
attrs.$observe('maxlines', function(val) {
maxLines = parseInt(val);
});
ngModel.$validators.maxlines = function(modelValue, viewValue) {
var numLines = (modelValue || '').split("\n").length;
return numLines <= maxLines;
};
attrs.$observe('maxlinesPreventEnter', function(preventEnter) {
// if attribute value starts with 'f', treat as false. Everything else is true
preventEnter = (preventEnter || '').toLocaleLowerCase().indexOf('f') !== 0;
if (preventEnter) {
addKeypress();
} else {
removeKeypress();
}
});
function addKeypress() {
elem.on('keypress', function(event) {
// test if adding a newline would cause the validator to fail
if (event.keyCode == 13 && !ngModel.$validators.maxlines(ngModel.$modelValue + '\n', ngModel.$viewValue + '\n')) {
event.preventDefault();
}
});
}
function removeKeypress() {
elem.off('.maxlines');
}
scope.$on('$destroy', removeKeypress);
}
};
});
NB: This does not restrict the number of lines if the user pastes in a value with more than the allowed number of lines, but it will correctly flag the field as invalid.
来源:https://stackoverflow.com/questions/26497492/limit-number-of-lines-or-rows-in-textarea