【问题标题】:angular.js textarea character count to exclude counting spaces and newlineangular.js textarea 字符计数以排除计数空格和换行符
【发布时间】:2016-12-24 22:36:48
【问题描述】:

我的 textarea 字段需要对字符进行计数,以根据定义的最大长度显示剩余的字符数。 但是当用户输入空格/换行符或从其他地方粘贴文本时,计数会出错。

我需要知道 Angular 是否有任何指令或方法来支持排除空格/换行符。

<textarea class="form-control"  maxlength="{{desc}}" my-maxlength = "{{desc}}" maxlen="maxlen" type="text" ng-model="problem.DESCRIPTION" aria-describedby="qDesc" id="questionDescription" name="questionDescription" ng-required="caseType" lang-check></textarea>
<p ng-show="problem.DESCRIPTION.length > (desc-5)" class="text-danger pull-right" id="qDesc">{{ desc - problem.DESCRIPTION.length}} {{ resource["textcount.sublabel.maximumcharacters"] }</p>

【问题讨论】:

    标签: javascript angularjs html


    【解决方案1】:

    您可以制作一个过滤器来返回非空白字符的数量

    yourModule.filter('charCount', function() {
        return function(text) {
            return (text.match(/\S/g) || []).length;
        };
    })
    

    并在你的模板中使用它

    problem.DESCRIPTION | charCount
    

    【讨论】:

      【解决方案2】:

      这里有你需要的angularjs解决方案,试试用

      ng-trim="假"

      文本区域。这是一个例子

      <body ng-app>
         <textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>
         <span>{{1500 - test.length}} left</span>
      </body>
      

      【讨论】:

      • 我不明白这将如何帮助 OP “支持排除空格/换行符”
      【解决方案3】:

      你不能只在ng-show{{}}中运行problem.DESCRIPTION.length,它不会运行,你必须创建一个函数并插入ng-show{{}}

      在您的控制器中创建一个函数来删除字符串的空格并返回其长度

      JS:

      $scope.countLength = function(str){
          if (str==undefined){
              return 0;                    
          }
          else{
              return str.replace(/ /g,'', '').length;  
          }
      }
      

      HTML:

      <p ng-show="countLength(problem.DESCRIPTION) > (desc-5)" class="text-danger pull-right" 
      id="qDesc">{{ desc - countLength(problem.DESCRIPTION)}} 
      {{ resource["textcount.sublabel.maximumcharacters"] }</p>
      

      看这里的例子: JSFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多