angular.js - Angularjs如何限制textarea输入字数?

浏览:27日期:2023-02-05

问题描述

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

问题解答

回答1:

<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);} };}回答2:

使用 $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个字符} }})回答3:

你可以这样:在textarea上绑定一个变量ng-model='length',统计你现在的字数,然后在绑定一个变量通过ng-disabled='length>=140'让textarea变disabled,或者弹出框什么的,反正就是监控输出框的字数。

回答4:

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

相关文章: