gpt4 book ai didi

angularjs - 限制文本区域中的行数(或行数)

转载 作者:行者123 更新时间:2023-12-01 19:18:55 25 4
gpt4 key购买 nike

我在 jQuery 和 JS 中看到过一些关于此的示例。

http://jsfiddle.net/XNCkH/17/

我环顾四周,发现你可以限制长度(参见 fiddle )。我想知道是否有办法限制 AngularJS 中的行数或字符长度是否可行?

http://jsfiddle.net/7nxy4sxx/

<textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>

谢谢!

最佳答案

这是我使用 AngularJS 1.3 分支中新的 ngModel.$validators 管道提出的工作指令:

/*
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);
}
};
});

Working Plunkr

注意:如果用户粘贴的值超过允许的行数,这不会限制行数,但会正确地将字段标记为无效。

关于angularjs - 限制文本区域中的行数(或行数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26497492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com