How to trigger a method with the keyboard shortcut in AngularJS

How to trigger a method with the keyboard shortcut in AngularJS

Posted by: Hoa Nguyen | November 27, 2015
If you are, for example, working on a chat application, one of the features that the user expects is an ability to send a message with a keyboard shortcut. The example of a directive below shows how this can be achieved for Shift + Enter combination:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
.directive('sendMessage', function(){
return function (scope, element) {
var shiftDown = false;
element.bind("keydown", function (event) {
 
// sets shiftDown to true if the shift key (key code is 16) is pressed
if(event.which === 16) {
shiftDown = true;
}
 
// sends the message if "enter" is pressed and "shift" is being held down
if(event.which === 13 && shiftDown) {
event.preventDefault();
scope.send();
scope.$apply();
}
});
 
// sets shiftDown to false if the shift key has been released
element.bind("keyup", function (event) {
if(event.which === 16) {
shiftDown = false;
}
});
};
});
});
You can play with a simple chat app that uses this directive on CodePen, and fork the app on GitHub.
Source From Sysgears
Read Further on AngularJS Series
Get image dimensions with ng-flow
Get a base64 encoded image using ng-flow in AngularJS
How to trigger a method with the keyboard shortcut in AngularJS
Moving a page element without affecting its scope in AngularJS
Launch Ionic app with a web or email link
Braintree and Angular.JS drop in integration
Minification safe Angular.js
AngularJS : Multiple Views, Layout Template and Routing
AngularJS: Implementing Routes And Multiple Views
AngularJS : Fetching data from the server
Building Intuitive Frontend Interfaces with AngularJS – An Overview!

Comment