angular.js - How to limit textarea input word count in Angularjs?
phpcn_u1582
phpcn_u1582 2017-05-15 16:51:33
0
4
807

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_u1582
phpcn_u1582

reply all(4)
过去多啦不再A梦
<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);
        }
    };
}
PHPzhong

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个字符
        }
    }
})
曾经蜡笔没有小新

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.

Ty80

<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>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template