本文介绍了ng-maxlength 搞砸了我的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的文本区域,其中包含剩余的这么多字符"以及验证.当我使用 ng-maxlength 来验证我的表单时,只要长度达到最大长度,它就会重置我的字符数.这是 plunkr 有什么解决方法吗?

 
解决方案

当你的 textarea 超过 15 个字符时,result 变成 undefined —这就是 ng-min/maxlength 指令的工作方式.我认为您必须编写自己的指令.这是一个将在 15 个字符后阻止输入的指令:

app.directive('myMaxlength', function() {返回 {要求:'ngModel',链接:函数(范围、元素、属性、ngModelCtrl){var maxlength = Number(attrs.myMaxlength);函数来自用户(文本){if (text.length > maxlength) {var transformInput = text.substring(0, maxlength);ngModelCtrl.$setViewValue(transformedInput);ngModelCtrl.$render();返回转换输入;}返回文本;}ngModelCtrl.$parsers.push(fromUser);}};});

更新:允许超过 15 个字符,但当计数超过 15 时禁用提交按钮:

link: function (scope, element, attrs, ngModelCtrl) {var maxlength = Number(attrs.myMaxlength);函数来自用户(文本){ngModelCtrl.$setValidity('unique', text.length 

I'm trying to do a simple textarea with "so many chars remaining" along with validation.when I use ng-maxlength to validate my form, it resets my charcount as soon as the length hits the max length. Here's the plunkr Any workarounds?

  <body ng-controller="MainCtrl">
    <div ng-form="noteForm">
      <textarea ng-maxlength="15" ng-model="result"></textarea>
      <p>{{15 - result.length}} chars remaining</p>
      <button ng-disabled="!noteForm.$valid">Submit</button>
    </div>
  </body>
解决方案

When your textarea exceeds 15 characters, result becomes undefined — that's just how the ng-min/maxlength directives work. I think you'll have to write your own directive. Here is a directive that will block input after 15 characters:

<textarea my-maxlength="15" ng-model="result"></textarea>
app.directive('myMaxlength', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      var maxlength = Number(attrs.myMaxlength);
      function fromUser(text) {
          if (text.length > maxlength) {
            var transformedInput = text.substring(0, maxlength);
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
            return transformedInput;
          }
          return text;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  };
});

Update: to allow more than 15 characters, but disable the submit button when the count exceeds 15:

link: function (scope, element, attrs, ngModelCtrl) {
  var maxlength = Number(attrs.myMaxlength);
  function fromUser(text) {
      ngModelCtrl.$setValidity('unique', text.length <= maxlength);
      return text;
  }
  ngModelCtrl.$parsers.push(fromUser);
}

这篇关于ng-maxlength 搞砸了我的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 18:32