当ng-minlength和ng-pattern在angularjs中定义时,长度计数错误

时间:2014-08-04 04:07:38

标签: javascript regex angularjs

当我定义ng-minlength和ng-pattern时,此代码不能正常工作:

<span class="myForm_textarea" ng-show="myFormZR.textarea.$dirty"><br /><br />characters : {{0 + myForm.textarea.length}} writed / 500 limit</span>
当字符串匹配正则表达式或计数为0直到达到最小长度时,

count变为0。我为此做了一个傻瓜:http://plnkr.co/edit/R6kGJmlQ4TgGf16kAmYi?p=preview

2 个答案:

答案 0 :(得分:2)

在angularjs 1.2.x中,您可以通过编写自定义指令来恢复无效值来解决此问题。

app.directive('allowInvalid', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    priority: 1, // force the postLink below to run after other directives
    link: function (scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function (viewValue) {
        return (viewValue === undefined) ? modelCtrl.$viewValue : viewValue;
      });
    }
  }
});

并将其放入textarea:

<textarea ng-model="myForm.textarea" ng-required="true" ng-minlength="5" ng-maxlength="500"  ng-pattern="textareaRegex" allow-invalid></textarea>

示例plunker: http://plnkr.co/edit/H0YePKFwkvaBZgnxCRMB?p=preview

答案 1 :(得分:-1)

如果要限制textarea中的最大字符数,可以使用maxlength属性(除了ng-maxlength):

<textarea ng-maxlength="500"  maxlength="500" />