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

16 javascript angularjs

当达到最大字符数时,如何阻止用户在textarea中键入更多字符?

我现在正在使用ng-keypress,但我无法弄清楚如何在达到限制时阻止输入.用户不应该在该textarea中输入或粘贴超过1000个字符.

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

Plunker链接.

    $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;
    };
Run Code Online (Sandbox Code Playgroud)

HTML

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

解:

我的错误是我只是在某个地方有一个错字,但给定的答案不是100%好.而不是使用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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

Ijo*_*chy 18

您应该尝试使用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>
Run Code Online (Sandbox Code Playgroud)


Ras*_*lom 14

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

你也可以设置一个值的手表:

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

  • 这样的事情:http://plnkr.co/edit/2Cux32XJEcCYoeiksdgp?p = preview? (2认同)

Max*_*tin 8

指令方式:

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;
            }
          });
        }
    }   
});
Run Code Online (Sandbox Code Playgroud)

演示 plunker


Dan*_*ell 6

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

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


小智 5

<input type="text" name="usrname" maxlength="10">
Run Code Online (Sandbox Code Playgroud)

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