AngularJS Live Example

by Pankaj Parkar

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc5.min.js"></script>
<body ng-app="HelloApp">
  <form name="createForm">
    <textarea name="cSep" rows=5 ng-model="cSep" ng-trim="false" type="text" class="form-control" allow-tab ng-maxlength="10"></textarea>
    <label ng-show="createForm.cSep.$error.allowTab && !createForm.cSep.$pristine" class="error">
      Column separator required (1-10 characters)
    </label>
  </form>
</body>

JavaScript

angular.module('components', [])
  .directive('allowTab', function() {
    return {
      require: 'ngModel',
      link: function(scope, ele, attrs, c) {
        c.$viewChangeListeners.push(function() {
          console.log('-- viewChangeListener --', JSON.stringify({
            ngModel: {
              viewVal: c.$viewValue,
              modelVal: c.$modelValue
            }
          }))
        });
        ele.bind('keydown keyup', function(e) {
          var val = this.value;

          console.log('Value ', val, val.split('\n'), this.selectionStart);
          if (e.ctrlKey && e.keyCode === 66 && e.type === 'keydown') { // Ctrl + B

            // get caret position/selection
            var start = this.selectionStart,
              end = this.selectionEnd,
              rowNum = this.value.substr(0, this.selectionStart).split("\n").length,
              values = val ? val.split('\n'): [""],
              currentRow = values[rowNum - 1];
              debugger
            // set textarea value to: text before caret + tab + text after caret
            currentRow = currentRow.substring(0, start) + '\t•' + currentRow.substring(end);
            this.value = values.join('\n');

            // put caret at right position again
            this.selectionStart = this.selectionEnd = start + 2;

            e.preventDefault();

            // prevent the focus lose
            return false;
          }
        });

        function getLineNumber(textarea, indicator) {
          indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
        }
      }
    }
  });

angular.module('HelloApp', ['components'])