Angular retrieves elements between indexes following ordering

After applying the orderBy on a table, the ordering is lost and the values of $index are from the sorted array rather than the original one. For example, if you have an items array with values

['orange', 'banana','potato','apple']
in your ng-repeat, after sorting, they will be displayed as:

- apple   $index = 0
- banana  $index = 1
- orange  $index = 2
- potato  $index = 3

If you attempt to select multiple items between apple($index = 0) and orange($index = 2), you might think this code would work:

for(index = 0; index <= 2; index++)
  console.log(items[index])

But it will actually print : [orange, banana, potato]; not [apple, banana, orange].

I'm searching for a method to determine the indexes within the displayed array post orderBy, any suggestions?

EDIT: Let's say that on the interface you have sorted the items and then selected apple followed by orange:

✓ apple
  banana
✓ orange
  potato

I am interested in knowing the items between those two selections, so I can choose all in-between, such as banana.

Answer №1

The best way to tackle this problem is by filtering the array beforehand in the controller and then performing operations on it.

$scope.filteredItems = $filter("filter")($scope.Items, "+");

$scope.handleSelection = function(startIndex, endIndex){
  //...
  $scope.selectedItems = $scope.filteredItems.slice(startIndex, endIndex);
}

When displaying in the View, make sure to use ng-repeat directly over filteredItems:

<div ng-repeat="item in filteredItems">
  {{item}}
</div>

Answer №2

A way to accomplish this is by using a custom filter, as explained in detail here

app.filter('index', function () {
    return function (array, index) {
        if (!index)
            index = 'index';
        for (var i = 0; i < array.length; ++i) {
            array[i][index] = i;
        }
        return array;
    };
});

In your HTML:

<tr ng-repeat="item in items | index | orderBy:'Store.storeName'">

By doing so, you can use item.index instead of $index within the HTML.

This technique works well with collections of objects.

It's important to note that this custom filter should be the first one applied in the list of filters (such as orderBy), and it will add an additional property (index, which can be customized) to each object in the collection.

Answer №3

With Angular, you have the ability to define a label for the information once filters have been executed. This label can then be passed into the method responsible for selecting the items, along with the specific item or the $index, which represents the position of the item within the ordered list.

 <div ng-repeat="item in items | orderBy: '+' as orderedItems">
    <a ng-click="itemSelected(orderedItems, $index)">{{item}}</a>
 </div>

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

Prevent scrolling in AngularJS model popups

When loading data for the first time in a model popup, the scroll bar is not displayed inside the popup. However, after performing a search function and filtering the data, the scroll bar appears inside the model popup. How can this issue be fixed? this ...

Invoke the wrapper function within the jQuery AJAX `complete` callback

I am currently trying to accomplish a task, but I keep receiving an error message stating that I cannot bind to undefined. I suspect this is happening because I am working within an anonymous function. My goal is to be able to access the method (getAndSayH ...

Is there a way to alter the color of an item just by clicking on it?

Looking to enhance my programming skills, I am interested in changing the color of an item to a series of colors upon clicking. I am weighing the options between CSS, javascript, and JQuery to achieve this effect. Which approach would be the most optimal ...

Load a file in JavaScript without using the cache

I'm working on a function that reads a text file from a specific location: <html> <head> <script> function readTextFile(file){ var out_text='' var rawFile = new XMLHttpRequest(); rawFile ...

Steps to sending a parameter to an AngularJS $http success callback

In my AngularJS application, I have implemented the following code: $http.get('/plugin/' + key + '/js').success(function (data) { if (data.length > 0) { console.log(data); // Here, I also need to retrieve the val ...

The issue with the Angular UI Bootstrap v0.11 datepicker popup functionality being unresponsive

Recently upgraded to UI Bootstrap version 0.11 and encountered an issue with the datepicker-popup functionality not working properly. Previously, everything was functioning correctly with version 0.10. Does anyone have insight into what changes were made ...

Are route segments mandatory in AngularJS?

My routing configuration currently appears like this: .when "/:locale", templateUrl: "/views/index.html" ... .otherwise redirectTo: "/en" The problem is that the initial route also matches /. Is there a method to include mandatory route segments, so th ...

Instructions for importing the 'child_process' module on the server side of a ReactJS application

Is there a proper way to utilize the 'child_process' module in a ReactJS application? ([email protected] / Linux) Various attempts have been made using different syntaxes without success: import { spawn } from 'child_process' ...

Convert the information within the data variable into a well-formatted JSON structure

I am attempting to transmit JSON information to the server utilizing the following URL: . The data variable is being populated with valid JSON containing properties such as name, email, and URLs. ...

Reorganizing an array to designate the first element as the primary key

Can the data in this array be simplified? Array ( [0] => Array ( [country_code] => IM [language_code] => GB ) [1] => Array ( [country_code] => GG [language_code] => JE ) [2] =& ...

What is the best way to reset the values in react-multiple-datepicker?

Having trouble clearing values assigned in react-multiple-datepicker library. import MultipleDatePicker from "react-multiple-datepicker"; import React from "react"; class Addjob extends React.Component { constructor(props) { super ...

Display the div with the matching data value when clicked, and conceal all other divs

I need help with a list of items in HTML using UL and LI tags. Each LI item has a specific data attribute value. What I am trying to achieve is that on clicking each LI item, another div with the same data attribute should be displayed while hiding all oth ...

What is the best way to store the pointer function abc(x, y) in an array using the code provided below?

Function Alpha This function acts as a pointer. char *alphaFunc(unsigned int a, unsigned int b) { //do something here ... } Function Beta Utilizes Function Alpha within its code. I am attempting to save the results of alphaFunc into ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

What are some methods for embedding HTML content onto a specific section of a webpage in a Node.js + Express application, without displaying it as the

Objective My goal is to insert a portion of HTML into a web page. Issue The page is not displaying properly with the desired styling and layout. I have a specific page that must be written in plain HTML rather than Jade, although I will still be usin ...

Quick and easy way to access json data with jquery

https://i.sstatic.net/kiEwe.png Need help with reading data from JSON format using jQuery. I've attempted the code below, but I'm having trouble retrieving the exact data I need. $.ajax({ url: '@Url.HttpRouteUrl("GetDistrictLi ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

Is it possible to rearrange the order of items in a JSON sequence?

Is it possible to rearrange the order of json items? For instance: [ { "category": "Science: Mathematics", "type": "multiple", "difficulty": "medium", "question": "In a complete graph G, which has 12 vertices, how many ed ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Executing PHP script using JavaScript via AJAX request

I need to execute a PHP script immediately upon clicking the Submit button without having to refresh the page. I attempted an AJAX call to achieve this, but it seems that the code provided does not work upon clicking. The login.php file is saved in the sa ...