title: AngularJS: Limiting the user input in custom contenteditable directive
body: <p>Using angular js here:</p>
  
  <p>I have a HTML table and using contenteditable for each row data, eg as below:</p>
  
  <pre><code>&lt;td contenteditable="true" 
      ng-repeat="column in targetTable.columns"
      ng-model="r[column.id]"
      ng-blur="!r.id? addNewRow(r[column.id], r): undefined"&gt;
  &lt;/td&gt;
  </code></pre>
  
  <p>I also have my directive as:</p>
  
  <pre><code>directive('contenteditable', ['$sce', function($sce) {
      return {
        link: function(scope, element, attrs, ngModel) {
  
          var regex =   /^[\w/\s_~`!@#$%^&amp;*()_+-={}[\]|\:;/&gt;\\\'\"]$/;      
          element.on('keypress', (e) =&gt; {
              char = String.fromCharCode(event.which);
              if (!regexpInt.test(char)) {
                  event.preventDefault();
              };         
          });
  
          ngModel.$parsers.push(function (value) {
             if (value.length &gt; 5) {
               value = value.substr(0, 5);
               ngModel.$setViewValue(value);
               ngModel.$render();
             }
             return value;
          });
        }
      }
  });
  </code></pre>
  
  <p>I am just posting relevant code from the directive. The entire working code can be seen in the code pen below.</p>
  
  <p>In the above directive I am using regex to allow user to type anything from the character set defined along with spl chars and space which works fine.</p>
  
  <p>I am also using ngModel.$parsers trying to restrict the user entry to certain character limit (5 in this case), so if the user types more than 5, I want to the input to stop accepting more chars. The reason to apply limit here is this I would be creating dynamic columns and based on the column name I would be applying the maxlength of each so I cannot apply the limit on the  in the html. </p>
  
  <p>Now the issue comes with the maxlength code, it works not exactly as expected. </p>
  
  <ul>
  <li><p>If you see the demo and start typing more than 5 characters, as soon as you type the 6th character the cursor comes to 1st character and keeps overwriting the existing if you type more chars.</p></li>
  <li><p>Since I want to allow space in the input, if you type some char and add space it tries to add &amp; n b s p; to the input.</p></li>
  </ul>
  
  <p>What I want from the maxlength code is, it should accept spaces and as soon as you try to type more than 5th char it would prevent the user to typing and stop there itself. Similar to regex code.</p>
  
  <p>Here is my below codepen demo:
  <a href="https://codepen.io/anon/pen/WKZJWw" rel="nofollow noreferrer">https://codepen.io/anon/pen/WKZJWw</a></p>
  
  <p>Any inputs for fixing this issue?    </p>