Skip to content

Instantly share code, notes, and snippets.

@lkatney
Created September 11, 2017 08:43
Show Gist options
  • Save lkatney/3219af271b8daa80ace96c44729d7da1 to your computer and use it in GitHub Desktop.
Save lkatney/3219af271b8daa80ace96c44729d7da1 to your computer and use it in GitHub Desktop.
Directive to use arrow keys on forms or tables to quickly jump on to input boxes
angular.module('app.directives')
.directive('arrowKeysIndex', function() {
return {
restrict: 'A',
require: '^ngModel',
link: function (scope, element, attrs) {
element.on('keydown', function(event) {
let currentIndex = attrs.arrowKeysIndex;
let nextIndex;
if (currentIndex === '' || currentIndex === null || typeof currentIndex === 'undefined') {
//don't do anything
}else{
let rowColumnIndex = currentIndex.split(':');
let row;
let column;
if(rowColumnIndex.length > 1){
row = parseInt(rowColumnIndex[0]);
column = parseInt(rowColumnIndex[1]);
}else{
row = parseInt(rowColumnIndex[0]);
}
//enter and down key
if (event.which === 13 || event.which === 40) {
nextIndex = (row+1)+':'+column;
event.preventDefault();
//up key code
}else if(event.which === 38){
nextIndex = (row-1)+':'+column;
event.preventDefault();
//left key code
}else if(event.which === 37){
nextIndex = row+':'+(column-1);
event.preventDefault();
//right key code
}else if(event.which === 39){
nextIndex = row+':'+(column+1);
event.preventDefault();
}
if(nextIndex){
var nextInput = angular.element(angular.element.find('[arrow-keys-index="'+nextIndex+'"]'));
nextInput.focus();
scope.$apply();
}
}
});
}
};
})
<table>
<tr ng-repeat="data in dataRows track by $index">
<td>
<input type="text" arrow-keys-index="{{$index}}:1" ng-model="data.column1" />
</td>
<td>
<input type="text" arrow-keys-index="{{$index}}:2" ng-model="data.column2" />
</td>
<td>
<input type="text" arrow-keys-index="{{$index}}:3" ng-model="data.column3" />
</td>
<td>
<input type="text" arrow-keys-index="{{$index}}:4" ng-model="data.column4" />
</td>
</tr>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment