This question already has an answer here:
I'm trying to get my controller to watch for a combination of keys. For argument's sake, let's say: up up down down left right left right b a. How can I get angular to look out for these regardless of where in the page the user currently is?
Here's my take on it:
What's different about this is it's a directive so if you attach this on the body, it'll apply to the whole page. This also allows for entering the code multiple times.
Plunkr:
http://plnkr.co/edit/tISvsjYKYDrSvA8pu2St
If you are trying 'ctrl+s' or 'commond+s' ( change the commondKey ) to do save, maybe can use like it :
directive :
element :
You can rename the saveEnter in directive, with change the save-enter in html.
The 'vm.saveTitle()' is the fuc your want to do.
Looks like you can use the ng-keydown to do this.
Here is a working plunker.
For this sample, I just bound
ng-keydown
to<body>
. Works pretty well to catch all the keyboard events globally.As @charlietfl points out,
ng-keydown
registers a lot of keyboard events so to make this usable would be a lot of work. For example, if you were trying to listen for a combination (likectrl
+r
), then thectrl
key will register many times.JS:
HTML:
I'm using a different way to do it.
Check out this plunker. I've implemented a simple '2 UP keystrokes in a row' scenario.
You can do it in plain jQuery and communicate the event with a
$rootScope.$broadcast
.Register the jQuery code in and Angular
run
callback (guarantees that angular has already bootstraped):and then any controller can listen to this event like:
Binding an
ng-keydown
action callback tobody
is ok, but has a small disadvantage. It fires a$digest
on every keystroke. What you really want is a$digest
only when the sequence has been entered when you somehow need to update the UI.EDIT
See comments on how to remove actual jQuery dependency.
Detecting Backspace-Key (Mac) and Del-Key (PC):