How to use a keypress event in AngularJS?
My simplest approach using just angular build-in directive:
ng-keypress
, ng-keydown
or ng-keyup
.
Usually, we want add keyboard support for something that already handled by ng-click.
for instance:
<a ng-click="action()">action</a>
Now, let's add keyboard support.
trigger by enter key:
<a ng-click="action()"
ng-keydown="$event.keyCode === 13 && action()">action</a>
by space key:
<a ng-click="action()"
ng-keydown="$event.keyCode === 32 && action()">action</a>
by space or enter key:
<a ng-click="action()"
ng-keydown="($event.keyCode === 13 || $event.keyCode === 32) && action()">action</a>
if you are in modern browser
<a ng-click="action()"
ng-keydown="[13, 32].includes($event.keyCode) && action()">action</a>
More about keyCode:
keyCode is deprecated but well supported API, you could use $evevt.key in supported browser instead.
See more in https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
You need to add a directive
, like this:
Javascript:
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" my-enter="doSomething()">
</div>
Another simple alternative:
<input ng-model="edItem" type="text"
ng-keypress="($event.which === 13)?foo(edItem):0"/>
And the ng-ui alternative:
<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
An alternative is to use standard directive ng-keypress="myFunct($event)"
Then in your controller you can have:
...
$scope.myFunct = function(keyEvent) {
if (keyEvent.which === 13)
alert('I am an alert');
}
...