首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >限制行数(或行数)

限制行数(或行数)
EN

Stack Overflow用户
提问于 2014-10-21 22:31:57
回答 1查看 5K关注 0票数 2

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

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

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

http://jsfiddle.net/7nxy4sxx/

代码语言:javascript
复制
<textarea ng-model="test" ng-trim="false" maxlength="1500"></textarea>

谢谢!T

EN

回答 1

Stack Overflow用户

发布于 2014-10-21 23:02:32

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

代码语言:javascript
复制
/*
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);
    }
  };
});

工作普朗克尔

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26497492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档