Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial approach was to focus on a specific element in the ng-click function and then use the ng-keydown function to select other elements. However, this method does not seem to be working as expected.

<div ng-repeat="elem in listCtrl.availableElements" class="list-elem" ng-class="{ 'selected' : listCtrl.availableElements[$index].selected }" ng-click="listCtrl.listHandler($event, listCtrl.availableElements[$index])" ng-keydown="$event.shiftKey && ($event.which == 38 || $event.which == 40) && listCtrl.listHandler($event, listCtrl.availableElements[$index])">
    <div>
        {{elem.text}}
    </div>
</div>

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

SPFx WebPart - Tabbed Interface

I am new to developing SPFX WebParts and currently working on creating a Tab WebPart. The HTML appears to be rendering correctly, but I'm facing issues with the Javascript functionality not firing as expected. Any assistance or guidance on how to prop ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Oops! Looks like we encountered a fatal error while running the unit tests. Unfortunately, the unit

After setting up the project environment and successfully installing grunt, I attempted to run grunt in the terminal which resulted in the following output: https://i.stack.imgur.com/4xnll.png I proceeded to follow the steps. Running grunt build --env ...

Ways to dynamically update the content of an HTML table without the need to reload the page

I'm currently working on an HTML table that retrieves data from a database and includes a button for deleting selected records. Here is what the table layout looks like: name phone links john 6562 link1 link2 link3 ___________ ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

What is the process for integrating personalized routes in angular.js?

Currently, I have set up a route as follows: .state('home.blog', { url: "/blog", templateUrl: "blog.html", controller: "BlogController" }) The current route is localhost:3000/home/blog, but I want to change it to localhost:3000/blog. Desp ...

How can I temporarily turn off the animation on a directive in Angular JS to prevent it from animating during page load?

Check out this JSFiddle for the issue: http://jsfiddle.net/goodwill/ezNuj/ I have created a custom directive with the code below: myApp.directive('ngFadeIn', function() { return function(scope, element, attr) { if (element.is('tr, t ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Error with AngularJS: IE not showing dropdown options for MultiSelect

My application features a multiselect dropdown menu that shows a list of countries. While this dropdown functions correctly in Chrome, it displays options differently in IE as shown below: https://i.stack.imgur.com/xhOmV.png I have attempted to adjust th ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...

Securely accessing Service Stack REST API with AngularJS and $http.get by providing authentication details

Currently, I am utilizing a service stack web service that has the CorsFeature enabled. My approach involves calling a service using AngularJS's $http.get method while setting withCredentials to true: $http.get(url,{ withCredentials: true}) I am se ...

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

How can I update the title of the NavigationBarRouteMapper without altering the current route in React Native?

Here is a snippet of code that outlines the NavigationBarRouteMapper: var NavigationBarRouteMapper = { ... , RightButton(route, navigator, index, navState){ return( <TouchableHighlight onPress={()=>{ //When this ...