我见过这个在jQuery和JS的一些例子。
I've seen some examples in jQuery and JS about this.
http://jsfiddle.net/XNCkH/17/
我一直在寻找周围,我可以看到,您可以限制的长度(见小提琴)。我不知道是否有办法来限制AngularJS或者字符长度是要走的路行或行数?
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?
http://jsfiddle.net/7nxy4sxx/
<textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>
谢谢!ŧ
Thanks! T
下面是我想出了一个工作指令,使用新的 ngModel。$验证
管道中AngularJS 1.3分支:
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);
}
};
});
工作Plunkr
注意::此不大于线的允许数量的限制,如果用户糊剂行中的值的数目,但它会正确检举字段为无效
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.