The best way I think is to use the tabindex
to locate elements for focus. Try something like this;
<li class="list-item" ng-repeat="item in items"
tabindex="{{item.tabIndex}}"
ng-class="item.selected"
ng-keydown="onKeydown(item, $event)" ng-focus="onFocus(item)">{{item.name}}
</li>
Then in your controller you want the Keydown handler;
var KeyCodes = {
BACKSPACE : 8,
TABKEY : 9,
RETURNKEY : 13,
ESCAPE : 27,
SPACEBAR : 32,
LEFTARROW : 37,
UPARROW : 38,
RIGHTARROW : 39,
DOWNARROW : 40,
};
$scope.onKeydown = function(item, $event) {
var e = $event;
var $target = $(e.target);
var nextTab;
switch (e.keyCode) {
case KeyCodes.ESCAPE:
$target.blur();
break;
case KeyCodes.UPARROW:
nextTab = - 1;
break;
case KeyCodes.RETURNKEY: e.preventDefault();
case KeyCodes.DOWNARROW:
nextTab = 1;
break;
}
if (nextTab != undefined) {
// do this outside the current $digest cycle
// focus the next element by tabindex
$timeout(() => $('[tabindex=' + (parseInt($target.attr("tabindex")) + nextTab) + ']').focus());
}
};
And a keep-it-simple focus handler;
$scope.onFocus = function(item, $event) {
// clear all other items
angular.forEach(items, function(item) {
item.selected = undefined;
});
// select this one
item.selected = "selected";
};
That's off the top of my head, in case it helps anyone coming across this thread like I did.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…