title: Angular directive - limit line count and length in textarea
body: <p>Building up on <a href="https://stackoverflow.com/questions/26497492/limit-number-of-lines-or-rows-in-textarea">this question</a>, I am trying to expand the solution to handle wrapping lines and pastes. My idea is to limit the number of characters per line and any characters over the limit will be regrouped onto a new line (for simplicity, I don't care if it will split a word in two).</p>
  
  <p>This is my version of the directive so far:</p>
  
  <pre><code>app.directive('textLimit', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elem, attrs, ngModel) {
  
        ReformatText();
  
        function ReformatText() {
          scope.result = scope.textEntry.replace('\n', ' ').match(/.{1,10}/g);
  
          //scope.textEntry = scope.result.join('\n');
  
          angular.element(elem).attr("rows", (scope.textEntry).split("\n").length);
        }
  
        elem.on('keydown', function(event) {
          if (event.keyCode == 13) {
            if ((scope.textEntry || '').split('\n').length &gt; 2) {
              event.preventDefault();
            }
          }
        });
  
        elem.on('keyup', function(event) {
          ReformatText();
        });
      }
    };
  });
  </code></pre>
  
  <p><a href="http://plnkr.co/edit/jjzzzGUTqYPDiNWNLKOc?p=preview" rel="nofollow noreferrer">See plunk here</a>.</p>
  
  <p>I call ReformatText() once in the beginning (to process any pre-loaded text) and once on every keystroke. On keydown, I check if it's the enter key and prevent it if there are already more than 2 newlines - then (regardless of what key it is) I want to reprocess the text in case anything was typed/pasted.</p>
  
  <p>My idea for ReformatText() is roughly this</p>
  
  <p>1) replace with spaces any existing newlines - these may be obsolete if the user edits an earlier row, also if they paste text that fits in the total limit I've set on the textarea but having more than 2 line breaks</p>
  
  <p>2) break the combined string into an array of 10-letter chunks (or whatever I want my length limit to be) - I came across many ways to do this and chose to use .match() with a regex</p>
  
  <p>3) overwrite the original property with the .join()ed array - this is the part that's failing, if I uncomment that line it behaves erratically. My guess is that I'm messing up the binding in some way.</p>
  
  <p>The sample input in the plunk shows what I'm trying to achieve - the result is getting formatted as I expect but I can't get it to bind back into the textarea.</p>
  
  <p>Is this a good approach - and if so what am I missing? Still new to JS and Angular and I've seen various suggestions on how to do similar things so I wonder if I'm on the right track.</p>