angular-keybind
:abc: :nut_and_bolt: A small AngularJS module to bind specific keypress events to methods.
At times you may need to attach specific functionality to an element based on specific key input.
For simple cases, AngularJS has a built in solution called ngKeyup
that works well. At
other times you may need something with a bit more power. angular-keybind was built to solve this
more complex use case.
:tv: Demo
Comments and Pull Requests welcome!
Contents
Installation
NPM
npm install angular-keybind --save
Bower
bower install angular-keybind --save
Manually
Add the script to your HTML:
<script src="../path/to/your/(npm|bower)_components/angular-keybind/dist/angular-keybind.js"></script>
##Dependencies
Usage
Include bc.AngularKeybind
as a dependency in your project:
angular.module('YourModule', ['bc.AngularKeybind']);
Use the directive as an attribute on any element that can be focused (it doesn't need to be an
input). It will listen for keypress events on the element and fire the associated method.
<input
bc-keybind
bc-keys="['13, '32']"
bc-method="vm.myMethod"
>
export class YourController {
constructor() {}
myMethod(event) {
console.log('One of our keys was pressed!');
console.log('Original event object: ', event);
}
}
:tv: Demo
Attributes
Most use cases will only need to use bc-keys
and bc-method
. For more advanced cases, a second
and third set of attributes can be used.
Attribute | Accepts | Details |
---|
bc-keys | Array | Expects an array of key codes |
bc-method | Method | Expects a method which will be called when a keypress matches one of the keys passed into bc-keys |
bc-keys2 | Array | Expects an array of key codes |
bc-method2 | Method | Expects a method which will be called when a keypress matches one of the keys passed into bc-keys2 |
bc-keys3 | Array | Expects an array of key codes |
bc-method3 | Method | Expects a method which will be called when a keypress matches one of the keys passed into bc-keys3 |
Learn more about keycodes on css-tricks
<input
bc-keybind
bc-keys="['13']"
bc-method="vm.myMethodForEnter"
bc-keys="['37', '38', '39', '40']"
bc-method2="vm.myMethodForArrows"
>
export class YourController {
constructor() {}
myMethodForEnter(event) {
console.log('One of the `bc-keys` keys was pressed! Pressed key: ', event.which);
}
myMethodForArrows(event) {
console.log('One of the `bc-keys2` keys was pressed! Pressed key: ', event.which);
}
}
:tv: Demo
Development
npm run build
- Build JSnpm run watch
- Watch JS and rebuild on changenpm run test
- Run testsnpm run watch:tests
- Watch for changes in .spec.js
files and re-run the tests