Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable carriage return with shift+return only

Tags:

angularjs

I'm using a textarea in a simple chat app. I'd like to enable the carriage return only when the user hits shift+return, and submit the form when the user hits the return key alone.

I'm using the ngKeydown directive. The problem is when I hit enter, the message is sent ok, the textarea is cleared and after that, a carriage return si inserted. It means the event keeps propagate...

Here is the HTML code:

<textarea ng-model="messageTyped" ng-keydown="checkReturn($event)"></textarea>

and here is the angularjs code:

function chatController($scope, ChatService) {

  $scope.messages = ChatService.messages

  $scope.checkReturn = function(event) {

    if (event.keyCode == 13 && !event.shiftKey) {

      event.stopPropagation() // <------ this line seems to have no effect

      // submit the message:
      if ($scope.messageTyped) {

        ChatService.SendMessage($scope.messageTyped)
        $scope.messageTyped = ""

      }
    }
  }
}

I don't know what I'm missing... Thanks for your help !

like image 818
ybycode Avatar asked Aug 13 '13 14:08

ybycode


1 Answers

I would suggest writing a custom directive for this. Then you could reuse it for any elements you'd like. Here is an example of using it to move to the next input element. Just put enter-next in whatever element you want to have this ability.

.directive('enterNext', function() {
  return {
    restrict: 'A',
    link: function($scope,elem,attrs) {
      elem.bind('keydown', function(e) {
        var code = e.keyCode || e.which;
        if ((code === 13) && (e.shiftKey)) {
          e.preventDefault();
          elem.nextAll('input').first().focus();
        }
      });
    }
  }
});
like image 109
Zack Argyle Avatar answered Sep 29 '22 11:09

Zack Argyle