限制Textarea中的行数(或行数)

时间:2014-10-21 22:31:57

标签: angularjs textarea

我在jQuery和JS中看到了一些关于此的例子。

http://jsfiddle.net/XNCkH/17/

我一直在四处寻找,我可以看到你可以限制长度(见小提琴)。我想知道是否有办法限制AngularJS中的行数或行数,或者字符长度是否可行?

http://jsfiddle.net/7nxy4sxx/

<textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>

谢谢! Ť

1 个答案:

答案 0 :(得分:5)

这是我提出的一个工作指令,使用AngularJS 1.3分支中的新ngModel.$validators管道:

/*
maxlines attribute directive, specify on a <textarea> to validate the number
of lines entered is less than the specified value.

Optional attributes:
   maxlines-prevent-enter: Specify as false to NOT block the pressing of the Enter
    key once the max number of lines has been reached.
*/

app.directive('maxlines', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      var maxLines = 1;
      attrs.$observe('maxlines', function(val) {
        maxLines = parseInt(val);
      });
      ngModel.$validators.maxlines = function(modelValue, viewValue) {
        var numLines = (modelValue || '').split("\n").length;
        return numLines <= maxLines;
      };
      attrs.$observe('maxlinesPreventEnter', function(preventEnter) {
        // if attribute value starts with 'f', treat as false. Everything else is true
        preventEnter = (preventEnter || '').toLocaleLowerCase().indexOf('f') !== 0;
        if (preventEnter) {
          addKeypress();
        } else {
          removeKeypress();
        }
      });

      function addKeypress() {
        elem.on('keypress', function(event) {
          // test if adding a newline would cause the validator to fail
          if (event.keyCode == 13 && !ngModel.$validators.maxlines(ngModel.$modelValue + '\n', ngModel.$viewValue + '\n')) {
            event.preventDefault();
          }
        });
      }

      function removeKeypress() {
        elem.off('.maxlines');
      }

      scope.$on('$destroy', removeKeypress);
    }
  };
});

Working Plunkr

NB:如果用户粘贴的值超过允许的行数,则不会限制行数,但会将该字段正确标记为无效。