Search code examples
javascriptangularjseventsenter

AngularJS: If only enter key pressed


I found an example how to trigger an event if enter key pressed, but the problem is that this event triggered if any other button pressed at the same time. Especially, this problem is relevant for textarea, when Shift + Enter stands for expanding input vertically.

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

So the question is actually how to catch event, when ONLY Enter key pressed?


Solution

  • You can simply add another check for that i-e whether shift is pressed using event.shiftKey and do accordingly. Something like

    if(event.which === 13 && !event.shiftKey) {
    scope.$apply(function (){
                        scope.$eval(attrs.ngEnter);
                    });
    ...
    }