2014-10-21 71 views

回答

4

這裏是我想出了,用在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

注:這不限制數量如果用戶粘貼的行數超過允許的行數,則會將該行正確標記爲無效。

+0

如何超過限制顯示輸入的行數? – 2015-05-26 10:38:27

+0

@RazvanB。您需要擴展指令以在輸入之後添加一些標記,您將手動更新以作爲驗證程序功能的一部分,以顯示行數。 – GregL 2015-06-01 05:49:38