ng-maxlength screws up my model

后端 未结 7 870
忘掉有多难
忘掉有多难 2020-12-08 02:17

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 th

相关标签:
7条回答
  • 2020-12-08 03:12

    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);
        }
      }; 
    });
    

    fiddle


    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);
    }
    

    fiddle

    0 讨论(0)
提交回复
热议问题