Javascript 达到字符限制时,AngularJS 会阻止在 textarea 上输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27105108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:43:24  来源:igfitidea点击:

AngularJS prevent input on textarea when character limit is reached

javascriptangularjs

提问by Ijon Tichy

How can I stop an user from typing more characters into a textarea when a maximum amount of characters is reached?

当达到最大字符数时,如何阻止用户在文本区域中输入更多字符?

Im using ng-keypress right now but I can't figure out how to prevent the input when the limit is reached. The user should not be able to enter or paste more than 1000 characters in total into that textarea.

我现在正在使用 ng-keypress,但我不知道如何在达到限制时阻止输入。用户在该文本区域中输入或粘贴的字符总数不应超过 1000 个。

The question is about how to stop the input, not how to Count the Input lenght, this part is already working fine for me.

问题是关于如何停止输入,而不是如何计算输入长度,这部分对我来说已经很好用了。

Plunker link.

普拉克链接。

    $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

HTML

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    ng-keypress="updateBody($event)">
</textarea>
<p>
    {{commentLength}} remaining
</p>

Solution:

解决方案:

My mistake was I just had a typo somewhere but the given answer is not 100% OK. Instead of using the oldValueit is required to substring()the newValue. If you don't do that you can't paste a text that goes over the 1000 characters into the text area. Using the newValueallows you to paste and cut the text down to the Limit.

我的错误是我只是在某处打错了字,但给出的答案不是 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;
        }
    });

采纳答案by Rasalom

You can use 'ng-maxlength' from angular input functionality, and watch when value is invalid. https://docs.angularjs.org/api/ng/directive/input, but it won't block the possibility to input.

您可以使用角度输入功能中的“ng-maxlength”,并观察值何时无效。 https://docs.angularjs.org/api/ng/directive/input,但它不会阻止输入的可能性。

Also you could just set a watch for value:

你也可以只设置一个值:

$scope.$watch('value', function(newVal, oldVal) {
  if(newVal.length > 10) {       
    $scope.value = oldVal;
  }
});

回答by Ijon Tichy

You should try using maxlength attribute. The code would be something like

您应该尝试使用 maxlength 属性。代码将类似于

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    maxlength="1000">
</textarea>
<p>
    {{1000 - comment.Comment.body.length}} remaining
</p>

回答by Maxim Shoustin

Directive way:

指导方式:

app.directive('myBlock', function ($parse) {
    return {
        scope: {
          validLength: '='
        },
        link: function (scope, elm, attrs) {

          elm.bind('keypress', function(e){

            // stop typing if length is equal or greater then limit
            if(elm[0].value.length >= scope.validLength){
              e.preventDefault();
              return false;
            }
          });
        }
    }   
});


Demo in plunker

演示 plunker

回答by Daniel Bonnell

All of the answers here are overly complicated and fail to leverage the power of HTML5. All you need to do is add maxlength="1000"to your input element and this will prevent the user from typing more than 1000 characters. It will also clip any pasted input to maintain the limit. See the Docsfor more details.

这里的所有答案都过于复杂,无法利用 HTML5 的强大功能。您需要做的就是添加maxlength="1000"到您的输入元素,这将防止用户输入超过 1000 个字符。它还将剪辑任何粘贴的输入以保持限制。有关更多详细信息,请参阅文档

Note that maxlengthis not the same as ng-maxlength. ng-maxlengthsimply checks the length of the input and sets formName.$invalidif the input exceeds the limit. You can use both on the same input or textarea element.

请注意,maxlength这与ng-maxlength. ng-maxlength只需检查输入的长度并设置formName.$invalid输入是否超过限制。您可以在同一个 input 或 textarea 元素上使用两者。

回答by Thom

<input type="text" name="usrname" maxlength="10">

use maxlength in your HTML . this is easy and effective

在您的 HTML 中使用 maxlength 。这是简单而有效的

回答by Mr. Wonderful

Going through same problem, stumbled on this post. Below solution worked for me.

遇到同样的问题,偶然发现了这篇文章。以下解决方案对我有用。

<input type="text" data-ng-model="value" class="form-control" ng-pattern="/^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]$/" ng-maxlength="15" maxlength="15" placeholder="enter your text here...">

回答by Shidhartha Sankar Saikia

just adding the maxlength property to textarea solve the problem

只需将 maxlength 属性添加到 textarea 即可解决问题

<textarea maxlength="10"
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    ng-keypress="updateBody();">
</textarea>

回答by dbushy727

Although watchers do work, they are very costly due to the nature of the digest cycle, so if you need this functionality in many places you can access the change event and monitor the length.

尽管观察者确实可以工作,但由于摘要循环的性质,它们的成本非常高,因此如果您在许多地方需要此功能,您可以访问更改事件并监视长度。

// controller
$scope.monitorLength = function (maxLength) {
  if ($scope.value.length > maxLength) {
    $scope.value = $scope.value.substring(0, maxLength);
  }
}

// html
<textarea ng-model="value" ng-change="monitorLength(1000)"></textarea>

回答by Ji?í Machá?ek

This works for me in template.

这在模板中对我有用。

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    maxlength="1000">
</textarea>
<p>
    {{1000 - (comment.Comment.body.length || 1000)}} remaining
</p>

回答by Mirza Kujundzic

You can do this to block it

你可以这样做来阻止它

    $scope.$watch('value', function(newVal, oldVal) {
        if(newVal == undefined){
            $scope.value= oldVal;
        }
    });

    <textarea ng-maxlength="10" ng-model="value" ></textarea>