ybycode ybycode - 1 year ago 99
AngularJS Question

How to enable carriage return with shift+return only

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) {

$scope.messageTyped = ""


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

Answer Source

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)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download