Disabling input using angular in editable for content

I want nothing to happen if you press enter when in editable for content:

this is what i tried inside the directive:

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

Here is the whole 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);
              }
          }
      };
  });
+4
source share
3 answers

I ended up like this:

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

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

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

This seems to be enough to achieve this:

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

The trick is to populate the event at startup, so subsequent startup never starts.

0
source

Source: https://habr.com/ru/post/1530416/


All Articles