【问题标题】:Limit Number Of Lines (or Rows) in Textarea限制 Textarea 中的行数(或行数)
【发布时间】:2014-10-21 22:31:57
【问题描述】:

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

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

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

http://jsfiddle.net/7nxy4sxx/

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

谢谢! T

【问题讨论】:

    标签: angularjs textarea


    【解决方案1】:

    这是我提出的一个工作指令,使用 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

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

    【讨论】:

    • 如果超出限制,如何显示输入的行数?
    • @RazvanB。您需要扩展指令以在输入之后添加一些标记,作为验证器功能的一部分手动更新以显示行数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多