Himmators
Himmators

Reputation: 15006

Disabling enter with angular in a content-editable

I want nothing to happen if you press enter while in a content-editable:

this is what I tried inside a directive:

element.on('blur keyup change', function (e) {
                        if(e.which == '13')
                            e.preventDefault();

Here is the entire directive:

    .directive('contenteditable', function () {
      return {
          restrict: 'A', // only activate on element attribute
          require: '?ngModel', // get a hold of NgModelController
          link: function (scope, element, attrs, ngModel) {
              if (!ngModel) return; // do nothing if no ng-model

              // Specify how UI should be updated
              ngModel.$render = function () {
                  element.html(ngModel.$viewValue || '');
              };

              // Listen for change events to enable binding
              element.on('blur keyup change', function (e) {
                    if(e.which == '13')
                        e.preventDefault();
                    scope.$apply(readViewText);
              });

              // No need to initialize, AngularJS will initialize the text based on ng-model attribute

              // Write data to the model
              function readViewText() {
                    var html = element.html();
                    //cleaning out html for saving data.
                    console.log(html);
                    html = html.replace(/(<([^>]+)>)/ig,"");
                    /*  .replace(/<div><br\s*[\/]?><\/div>/gi,'')
                        .replace(/<div>/gi,'\n')
                        .replace(/<\/div>/gi,'')
                        .replace(/<br\s*[\/]?>/gi,'');*/
                    console.log(html)
                    ngModel.$setViewValue(html);
              }
          }
      };
  });

Upvotes: 5

Views: 1845

Answers (3)

Alo Sarv
Alo Sarv

Reputation: 376

It seems that this is sufficient to achieve this:

element.on('keydown', function(e) { if (e.keyCode == 13) { return false; } });

Trick being to nab the event at keydown so the later keyup never triggers.

Upvotes: 0

Himmators
Himmators

Reputation: 15006

I ended up doing like this:

      element.on('keydown', function (event){
            if(event.which == '13'){
                window.event.cancelBubble = true;
                event.returnValue = false;
                insertTextAtCursor('\n');
            }
      });

Upvotes: 4

Hamed Ali Khan
Hamed Ali Khan

Reputation: 1118

Try this, hope it works, else need to play with the code

ngModel.$parsers.unshift(function (inputValue) {
    var noEnter = inputValue.replace(/[\n]/g, "");
    ngModel.$viewValue = noEnter;
    ngModel.$render();
    return noEnter;
});

Upvotes: 0

Related Questions