Aleksey Kiselev
Aleksey Kiselev

Reputation: 331

AngularJS execute method on ng-keypress: Ctrl + Enter

I would like to submit text on click on the Ctrl + Enter, but I could not find out how to do that. My code 100% works for Enter or Ctrl separate keypress, for example:

<div ng-show="hiddenFriendId != null" ng-keydown="$event.which === 13 && sendMessage()">
    <textarea id="messageText" placeholder="Input your message here. Use Ctrl + Enter to send your message" cols="40" rows="3" my-maxlength="3" ng-model="messageText"></textarea>
</div>

But while I'm trying something like -

<div ng-show="hiddenFriendId != null" ng-keydown="($event.which === 13 && $event.which === 17) && sendMessage()">

it is not working (method execution begins on click on the Enter without Ctrl). Can anybody help me with that? I found examples only for a single keypress.

Upvotes: 2

Views: 3183

Answers (4)

ramgopaln
ramgopaln

Reputation: 11

No need of writing lines of code just insert code snippet

<input type="text" placeholder="Write a comment" ng-model="data" ng-keypress="($event.charCode==10)? myfunc() : return">

try using above code for Ctrl+Enter press event in the below link

https://jsfiddle.net/smqud8g0/2/

Upvotes: 1

felixhu
felixhu

Reputation: 41

You can do this with

// Inside your controller

public keyDownEvent = ($event) => {
  if ($event.ctrlKey && $event.keyCode === 13) {
      this.submit();
  };
}
<!-- In your template -->

<input type="text" value="inputValue" ng-keydown="$panelRow.keyDownEvent($event)">

Upvotes: 3

Slava Elantsev
Slava Elantsev

Reputation: 81

If you need Ctrl + Enter you could use if (($event.code == "Enter" && $event.which === 10)) If you need Shift + Enter you could use if (($event.shiftKey && $event.which === 13))

Upvotes: 0

Phillip Kemp
Phillip Kemp

Reputation: 63

I had the same question and found a simple solution here https://codepen.io/y__b__y/pen/afFec

All you have to do is create a custom directive on the attribute and use it. It worked like a boss for me:

DIRECTIVE

var app = angular.module('yourApp', []);

app.directive('enterSubmit', function () {
    return {
      restrict: 'A',
      link: function (scope, elem, attrs) {       
        elem.bind('keydown', function(event) {
          var code = event.keyCode || event.which;

          if (event.ctrlKey && code === 13) {
            if (!event.shiftKey) {
              event.preventDefault();
              scope.$apply(attrs.enterSubmit);
            }
          }
        });
      }
    }
  });

HTML

<textarea enter-submit="sendMessage()" /></textarea>

Hope this helps!

Upvotes: 0

Related Questions