Limit Number Of Lines (or Rows) in Textarea

心已入冬 提交于 2019-12-04 19:07:44

Here is a working directive I came up with, using the new ngModel.$validators pipeline in the AngularJS 1.3 branch:

/*
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: This does not restrict the number of lines if the user pastes in a value with more than the allowed number of lines, but it will correctly flag the field as invalid.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!