【发布时间】:2014-11-24 12:40:14
【问题描述】:
当达到最大字符数时,如何阻止用户在文本区域中输入更多字符?
我现在正在使用 ng-keypress,但我不知道如何在达到限制时阻止输入。用户在该文本区域中输入或粘贴的字符总数不应超过 1000 个。
问题是关于如何停止输入,而不是如何计算输入长度,这部分对我来说已经很好了。
$scope.$watch('comment.Comment.body', function (newValue, oldValue) {
if (newValue) {
$scope.commentLength = 1000 - newValue.length;
}
});
// Tried this, nothing stops it
$scope.updateBody = function (event) {
event.cancel();
event.stop();
return false;
};
HTML
<textarea
ng-model="comment.Comment.body"
name="comment[Comment][body]"
placeholder="Your comment..."
ng-keypress="updateBody($event)">
</textarea>
<p>
{{commentLength}} remaining
</p>
解决方案:
我的错误是我只是在某个地方打错了字,但给出的答案不是 100% OK。而不是使用oldValue,而是需要substring()newValue。如果不这样做,则无法将超过 1000 个字符的文本粘贴到文本区域中。使用newValue 可以将文本粘贴和剪切到限制。
$scope.$watch('comment.Comment.body', function (newValue) {
if (newValue && newValue.length > 1000) {
$scope.comment.Comment.body = newValue.substring(0, 1000);
}
// Must be checked against undefined or you get problems when removing text
if (newValue != undefined) {
$scope.commentLength = 1000 - newValue.length;
}
});
【问题讨论】:
-
使用 ng-keydown(而不是 ng-keypress)有帮助吗?
-
如果你还需要这个问题的答案,请在这个线程中查看答案,你必须编写一个自定义指令 -> stackoverflow.com/questions/17075969/…
标签: javascript angularjs