2016-08-18 119 views
0

我的textarea字段需要对字符进行计数,以显示相对于定义的最大长度剩余的字符数。 但是,当用户输入空格/换行符或从别处粘贴文本时,计数出错。angular.js textarea字符计数以排除计数空格和换行

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

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

回答

0

你可以做一个过滤器返回的非空白字符

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

的数量和使用,在您的模板

problem.DESCRIPTION | charCount 
0

这里是angularjs解决方案您需要尝试使用

纳克修整= “假” 中textarea的

。这里是例子

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

我不明白这是怎么回事,以帮助OP为* “支持的空间排斥/换行符计” * – Phil

-1

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