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 !
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();
}
});
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With