【问题标题】:Limiting words in textarea with AngularJS使用 AngularJS 限制文本区域中的单词
【发布时间】:2017-02-15 04:34:44
【问题描述】:

我一直在尝试使用 AngularJS 限制文本区域中的单词。 到目前为止,我已经尝试过这个

文本区域 HTML

<textarea ng-model="man_abs" style="height: 100px;" id="manuscriptabstract" name="manuscriptabstract" placeholder="Maximum 250 Words" class="form-control" ng-change="wordCount()" required=""></textarea>
<span class="help-block">{{251 - man_abs.split(' ').length}} words left</span>

AngularJS 脚本

$scope.wordCount = function() {
    if ($scope.man_abs != undefined) {
        var key_length = $scope.man_abs.split(' ').length;
        if (key_length >= 251) {
           $scope.man_abs = $scope.man_abs.substring(0, $scope.man_abs.lastIndexOf(" "));
           alert("You are allowed to enter only 250 words in this field");
        }
    }
}

我似乎工作正常,但是当我复制粘贴超过 250 个字的段落时,它没有按预期工作。

我尝试了 preventDefault() 方法,但它不起作用。 我需要确保用户不能输入超过 250 个单词,如果复制粘贴,则在第 250 个单词之后必须删除该句子..

【问题讨论】:

  • 任何理由你不只是使用maxlength="250"
  • 它实际上限制了字符,而不是单词。我试过了,我想做的是限制字数。
  • 抱歉 - 我没有注意到您限制的是单词而不是字符。
  • 没问题..完全
  • @SibiRaj 这是新手开发人员的问题。他们不接受解决方案。如果以下任何解决方案都不起作用,并且您找到了另一个有效的解决方案,请发布解决方案

标签: javascript html angularjs


【解决方案1】:

你也可以尝试使用这样的指令来限制单词:

.directive('myCheck', function () {
        return {
            restrict: 'AE',
            link: function (scope, element, attrs) {
                element.bind('keyup', function (e) {
                  console.log(this.value);
                  var words = this.value.split(" ");
                  console.log("words are:",words.length)
                  var tmp = '';
                  if (words.length >5){
                    for(var i=0;i<5;i++){
                      tmp += words[i] + ' ';
                    }
                    this.value = tmp;
                  } 
                });
            }
        }
});

转换成 HTML:

<input type="text" my-check> /*you can do it with textarea as well*/

plunker 示例:

https://plnkr.co/edit/7EeUbu1d96vCCQhi8g19?p=preview

【讨论】:

  • 谢谢,如果你觉得这个解决方案有用,可以加一票!
【解决方案2】:

你有两个选择:

  1. ng-click = wordCount()
  2. 使用 angular watch $watch 查看变化。

但我建议您使用ng-click 选项。因为它很容易并且不会在页面上产生负载/压力,因为 $watch 不会让页面休息。

例子:

&lt;textarea ng-model="man_abs" style="height: 100px;" id="manuscriptabstract" name="manuscriptabstract" placeholder="Maximum 250 Words" class="form-control" ng-change="wordCount()" ng-click="wordCount()" required=""&gt;&lt;/textarea&gt;

在控制器中

$scope.wordCount = function() { if ($scope.man_abs != undefined) { var key_length = $scope.man_abs.split(' ').length; if (key_length >= 251) { var trimmedString = $scope.man_abs.substring(0, 250); $scope.man_abs = trimmedString; alert("You are allowed to enter only 250 words in this field"); } } }

【讨论】:

  • 但是如何修剪句子,这是我的问题。
  • 它现在应该可以工作了,根据您的要求替换代码中的 250
  • 但是剪裁很棘手,当我复制粘贴时,会发生一些事情,在复制粘贴期间,它会随机剪裁,而不是在 250 字之后
  • >no index is given from 0th index to 250th index 只会被修剪。代码经过测试不能随便做事
  • 尝试在每个单词之间添加额外的空格,它只会在这种情况下发生,抱歉我的错误我没有完全解释。否则它很有效
【解决方案3】:

您可以创建自定义验证器

.directive('maxwords', [function () {
  return {
    require : 'ngModel',
    link : function (scope, elm, attrs, ctrl) {
      ctrl.$validators.maxwords = function (modelValue, viewValue) {
        if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
        }

        return (modelValue.match(/\S+/g) || []).length <= +attrs.maxwords;

      };
    }
  };
}])

并将其用作:

  <textarea maxwords="30"/>

error.maxwords 将像通常的验证一样被设置为敌人验证。

【讨论】:

    【解决方案4】:

    你也应该在粘贴事件上调用你的函数

    <textarea ng-model="man_abs" style="height: 100px;" id="manuscriptabstract" name="manuscriptabstract" placeholder="Maximum 250 Words" class="form-control" ng-change="wordCount()" ng-paste="wordCount()" required=""></textarea>
    <span class="help-block">{{251 - man_abs.split(' ').length}} words left</span>
    

    【讨论】:

    • 谢谢我添加了 ng-paste 但我可以在 250 字后粘贴,这就是问题所在
    • 然后在 ng-paste 事件上做一些数学逻辑,比如 var str = "Hello world!"; var res = str.substring(1, 4);现在,如果您的句子长度超过 250,然后像上面的示例一样减去您的句子
    【解决方案5】:

    你可以使用 $watch 来完成这个任务 试试这个代码:

    https://jsfiddle.net/jigarb1992/awLp4bnk/

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <div ng-app="myapp" ng-controller="myctrl">
        <textarea ng-model="txt" rows="10" cols="50"></textarea>
        <br>
        <span class="help-block">{{limit}} words left</span>
        </div>
    
    <script>
    var app = angular.module("myapp", []);
    app.controller("myctrl", function($scope){
        $scope.limit = 250;
        $scope.$watch("txt", function(newValue, lastValue){
         var words = $scope.txt.split(" ").length - 1;
        if(words > 250 ){
            $scope.txt = lastValue;
        }
        $scope.limit = 250 - words;
      })
    })
    </script>
    

    【讨论】:

    • 欢迎@sibiraj,所以你的回答是最好的
    【解决方案6】:

    您可以使用Array的Split和join方法。

    所以下面将适用于你的情况

     $scope.wordCount = function() {
            if ( $scope.man_abs != undefined ) {
              var key = $scope.man_abs.split( ' ' );
                if ( key.length >= 251 ) {
                $scope.man_abs = key.splice( 0, 250 ).join( ' ' );
               alert( "You are allowed to enter only 250 words in this field" );
                   }
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 2016-06-18
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2010-10-08
      • 2012-04-21
      • 1970-01-01
      • 2011-07-28
      相关资源
      最近更新 更多