angular.js - Angularjs如何限制textarea输入字数?
phpcn_u1582
phpcn_u1582 2017-05-15 16:51:33
0
4
741

一般情况下的输入可以做出限制,但是在移动端上,用输入法打出一大段文字再点击输入文本框内超出限制也还能继续输入。请问有什么其他的方法可以一直跟踪用户输入的字数,监控到超出了就弹出提示并且把超出的内容删掉?

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!