Thank you.
However, I need this in ES5, preferably in the following form:app.directive('focusNext', function() {return {restrict: 'A',link: function(scope, el) {el.bind('keydown', function(event) {if (event.keyCode === 13) {// 1. look for the next element here// 2. set focus to element}});}};});I compiled your code with Babel, but the TraverseAndFindFocusableElements it yields is a bit confusing, and doesn't work (regeneratorRuntime is not defined). Can you show me a simple way to find the index of the directives' element inside the among the other items with the same focus-next directive?I'm able to get the other items document, but none of the items seem to match "el".var els = document.querySelectorAll('[focus-next]')for(var i in els) {console.log(els[i]==el) // all of these return false}As you can probably tell, I'm very much a noob with Angular.
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
//es5 helper
function Es5TraverseAndFindFocusableElements(elm) {
var result = [];
inspect(elm);
return result;
function inspect(elm) {
if (elm.tabIndex > -1) {
result.push(elm);
}
var _arr = [].concat(_toConsumableArray(elm.children));
for (var _i = 0; _i < _arr.length; _i++) {
var child = _arr[_i];
inspect(child);
}
}
}
function focusNext() {
return {
restrict: "A", //make it an attribute selector
controller: focusNextController
};
/* ngInject() */
function focusNextController($element) {
var el = $element[0]; //grab the raw dom element!
this.$onInit = function () {
el.addEventListener('keydown', handleEnter);
};
this.$onDestroy = function () {
el.removeEventListener('keydown', handleEnter);
};
function handleEnter(ev) {
if (ev.keyCode === 13) {
ev.preventDefault();
// utilize the above generator and ES6 spread to build an array of focusable elements
// now using an ES5 helper.
var elmList = Es5TraverseAndFindFocusableElements(document.body);
var current = elmList.findIndex(function (n) {
return n == el;
});
var next = Math.min(elmList.length - 1, current + 1);
if (ev.shiftKey) {
//reverse on shift, make it on par with tab.
next = Math.max(0, current - 1);
}
elmList[next].focus();
}
}
}
}
angular
.module('nextEnter', [])
.directive('focusNext', focusNext);
<input ng-repeat="i in [1,2,3]" my-directive="i" ng-attr-tabindex="{{someController.calculateOrder(i)}}">