angular-ui / ui-codemirror

This directive allows you to add CodeMirror to your textarea elements.
http://angular-ui.github.io/ui-codemirror
MIT License
378 stars 193 forks source link

<textarea ui-codemirror> feedback: cursor error with ng-model #113

Open bdedardel opened 9 years ago

bdedardel commented 9 years ago

Hi,

Using textarea with ng-model, cursor returns at the position 0 if I press 'space' or 'enter' keys. It is OK without ng-model !

<textarea 
   id="mytextarea" 
   ng-model="myModel" 
   ui-codemirror="{
     lineNumbers: true,
     theme:'default',
     mode: 'xml'
   }">
 </textarea>
bdedardel commented 9 years ago

I worked on a patch that may help you for the next release: Let me know if you fix it.

Regards, Benjamin

// Keep the ngModel in sync with changes from CodeMirror
    codemirror.on('change', function(instance) {
      var modeDebug = false;
      var newValue = instance.getValue();

      // patch for enter key
      if (newValue.endsWith('\n')) {
        if (modeDebug) console.log('patch: last char is eol');
        var cursor = codemirror.getCursor();
        cursor.line += 1;
        cursor.ch = 0;
        codemirror.setCursor(cursor); // /!\ need to be improve with smart indent !
      }
      // patch for space key
      else if (newValue.endsWith(' ')) {
        if (modeDebug) console.log('patch: last char is a space');
        var cursor = codemirror.getCursor();
        cursor.ch += 1;
        // ngModel.$setViewValue(newValue); // DO NOT SET new value (trim it !)
        codemirror.setCursor(cursor);
      }       
      else if (newValue !== ngModel.$viewValue) {
        // BUG: cursor returns at position  0 using keys 'space' or 'enter'
        // => see previous patches
        scope.$evalAsync(function() {
            if (modeDebug) console.log('sync ng model');
            ngModel.$setViewValue(newValue);
        }); 
      }
    });
  }