search

Home  >  Q&A  >  body text

angular.js - How to limit textarea input word count in Angularjs?

Generally, input can be restricted, but on the mobile terminal, you can continue to input if the input method exceeds the limit by typing a large paragraph of text and then clicking on the input text box. Is there any other way to keep track of the number of words entered by the user, and when the number of words entered by the user is exceeded, a prompt will pop up and the excess content will be deleted?

phpcn_u1582phpcn_u15822786 days ago812

reply all(4)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-15 16:53:33

    <p ng-controller="TextareaCtrl">
        <textarea ng-model="text" ng-change="checkText()"></textarea>
    </p>
    
    function TextareaCtrl($scope)
    {
        $scope.checkText = function () {
            if ($scope.text.length > 5) {
                alert("text is too long");
                $scope.text = $scope.text.substr(0, 5);
            }
        };
    }
    

    reply
    0
  • PHPz

    PHPz2017-05-15 16:53:33

    Use $watch

    javascript$scope.content; //假设这是你textarea上的绑定
    var limitation = 150; // 假设文本长度为 150
    $scope.$watch('content', function(newVal, oldVal) {
        if (newVal && newVal != oldVal) {
            if (newVal.length >= limitation) {
                $scope.content = newVal.substr(0, limitation); // 这里截取有效的150个字符
            }
        }
    })
    

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 16:53:33

    You can do this:
    Bind a variable ng-model="length" to the textarea to count your current word count, and then bind a variable through ng-disabled="length>=140" to make the textarea disabled, or a pop-up box or something, anyway It is to monitor the word count of the output box.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-15 16:53:33

    <p ng-controller="myNoteCtrl">

    <textarea ng-model="message" cols="40" rows="10" maxlength="{{ max }}"></textarea>
    <p>
        <button ng-click="save()">保存</button>
        <button ng-click="clear()">清除</button>
    </p>
    <p>Number of characters left: <span ng-bind="left()"></span></p>    

    </p>

    <script>

    var app = angular.module("myNoteApp", []);
    app.controller("myNoteCtrl", function($scope) {
        $scope.max = 100;
        $scope.message = "";
        $scope.left  = function() {
            return 100 - $scope.message.length;
        };
        $scope.clear = function() {$scope.message = "";};
        $scope.save  = function() {alert("Note Saved");};
    });

    </script>

    reply
    0
  • Cancelreply