Check out this functional plunker example
This is the provided HTML code snippet:
<div tabindex="{{$index}}" ng-keydown="moveCursor($event)" ng-repeat="elem in elements" ng-click="setCursor($index)">
<span ng-class="{ 'selected' : elements[$index].selected }">{{$index}} : {{elem.text}}</span>
</div>
The use of tabindex
ensures focus on the element.
Upon ng-click
, a cursor is set for selection purposes.
$scope.setCursor = function(index){
var wasSelected = $scope.elements[index].selected;
$scope.unselectAll();
$scope.elements[index].selected = !wasSelected;
$scope.cursor = index;
$scope.initialCursor = index;
}
The cursor serves as a reference point for selecting other elements, with initialCursor
saving the starting position.
Event handling and lock management are done within ng-keydown
.
$scope.moveCursor = function(event){
if(event.shiftKey && event.which == 38){
if($scope.cursor > 0){
$scope.selectUp();
}
}else if(event.shiftKey && event.which == 40){
if($scope.cursor < $scope.elements.length-1){
$scope.selectDown();
}
}
}
selectUp()
and selectDown()
functions exhibit similar behaviors:
$scope.selectDown = function(){
if($scope.cursor < $scope.initialCursor){
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
$scope.cursor += 1;
}else{
$scope.cursor += 1;
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
}
}
$scope.selectUp = function(){
if($scope.cursor > $scope.initialCursor){
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
$scope.cursor -= 1;
}else{
$scope.cursor -= 1;
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
}
}
Focus now on the implementation of the selectUp
method.
Two distinct behaviors need to be implemented:
If ahead of initial click when selecting upward, move to next item upwards.
If behind initial click when selecting upward, undo selection of last item chosen.
Hoping this explanation proves beneficial.
If dissatisfied with this approach, consider utilizing the "tabindex" suggestion to craft your own solution.