相关疑难解决方法(0)

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

当达到最大字符数时,如何阻止用户在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 …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs

16
推荐指数
5
解决办法
5万
查看次数

输入文本字符数限制

我希望我的文本框只允许数字,并且也有字符限制。

目前,我的数字正在工作......现在我在弄清楚如何限制字符方面遇到问题。

这是我所拥有的...

JS:

app.directive('numbersonly', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('keydown', function (event) {
                if (event.which == 64 || event.which == 16 && elm.val().length > 4) {
                    return false;
                } else if (event.which >= 48 && event.which <= 57) {
                    return true;
                } else if (event.which >= 96 && event.which <= 105) {
                    return true;
                } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1 && elm.val().length > 4) …
Run Code Online (Sandbox Code Playgroud)

validation input angularjs angularjs-directive angularjs-scope

4
推荐指数
1
解决办法
2万
查看次数