Sort the array before applying pagination

My HTML looks like this:

<div class="creations accordion" ng-repeat="creation in filteredCreations | orderBy : field : reverse">
   [[creation.id]]
   [[creation.name]]
</div>

In my Angular controller, I have the following setup:

var exampleApp = angular.module('exampleApp', ['ui.bootstrap']).config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[').endSymbol(']]');
});

exampleApp.controller('CreationController', ['$scope', '$filter', function($scope, $filter) {
    $scope.currentPage = 1;
    $scope.itemsPerPage = 2;

    creations = $.map(creations, function(value, index) {
        return [value];
    });
    $scope.creations = creations;
    $scope.filteredCreations = [];

    $scope.order = function(field) {
      $scope.reverse = ($scope.field === field) ? !$scope.reverse : false;
      $scope.field = field;
    };
    $scope.field = 'id';
    $scope.reverse = false;

    $scope.figureOutCreationsToDisplay = function() {
        var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
        , end = begin + $scope.itemsPerPage;

        $scope.filteredCreations = $scope.creations.slice(begin, end);
    };

    $scope.figureOutCreationsToDisplay();

    $scope.pageChanged = function() {
        $scope.figureOutCreationsToDisplay();
    };
}]);

I currently paginate the results and then display them, meaning the orderBy filter only sorts the data within the paginated set. However, I now want to sort all the data before pagination.

How can I achieve this?

Answer №1

To ensure the correct ordering of the list, it is necessary to execute the orderBy function in the controller before rendering the list. If there are any triggers that modify the order of the items, simply call the sort function in the controller. The following link provides guidance on how to utilize Angular's orderBy function in the controller without having to create a custom solution:

$scope.filteredCreations = $filter('orderBy')(itemsArray, "field")

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

What is the reason for the DOMException constructor deriving directly from Function.prototype, while the DOMException prototype derives directly from Error.prototype?

Why is DOMException different from AggregateError, EvalError, and others in terms of its prototype chain? Both of these statements are true: Object.getPrototypeOf(DOMException) === Function.prototype Object.getPrototypeOf(DOMException.prototype) === Error ...

The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no erro ...

Using AJAX to send a POST request with an array

My issue is that when using jQuery.ajax to post data to an action page, I am encountering a problem with the variable arrControlls. jQuery.ajax({ type: "POST", url: "../ajax/si-notificar_investigacion.php", data: { idincidente: $("#idi ...

Angular's approach to inter-controller communication

Exploring the optimal way to share properties or state between controllers/directives in Angular. Various methods exist, but I'm aiming for following best practices. Here are some basic examples of implementation: 1. Leveraging $scope.$watch // Pare ...

Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code: $scope.redirect = function () { const params = $httpParamSerializer({ initval: { user: { id: 1, ...

jQuery: Read the character string until the occurrence of symbols "{" and "}" (language variation on the website)

Trying to extract text enclosed in curly brackets { } While managing content in three different languages simultaneously. For example: {:en}Resources List{:}{:ru}Список Ресурсов{:}{:uk}Список Ресурсів{:} If the current languag ...

Setting up an Express route with dynamic parameters in Node.js

I am in the process of creating a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I'm working on setting up an Express route that will retrieve specific data from MongoDB based on the provided ID. Here is the current code snippet for the ro ...

Interruption of client-side JavaScript by the ASP timer tick event

Exploring the Situation In the realm of web development, I find myself immersed in creating a web application dedicated to monitoring various services. Each service is equipped with an UpdatePanel, showcasing status updates along with interactive buttons ...

ClearMedia Logo PredictiveText MaterialUi

I am trying to display the MUI Autocomplete clear text icon every time I enter text. Currently, it only shows when I select an option, not when I type anything. https://i.sstatic.net/ekwES.png https://i.sstatic.net/8wkpm.png ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Bug occurring when inserting Ajax content into a field without refreshing the second page

Recently, I followed a tutorial on how to submit a form without refreshing the page using jQuery. Instead of using PHP as recommended in the tutorial, I decided to create my own classic ASP page. However, I encountered a problem - when I try to input space ...

Third-party authentication is redirecting AJAX calls within the same domain

Our asp.net core application requires an AJAX call to be made to an IIS 8.0 Server that is protected by CA SiteMinder SSO. When making Get requests using AJAX, the desired response is received. However, when Put or Post requests are made, a 302 response i ...

accordion menu: stuck in my list like a trapped diver due to the overflow

I need assistance with creating a side menu. Here is the current code I have: function opensubmenus() { $('#submenus').css("display", "block"); } #menus { overflow-y: scroll; width: 150px; background-color: blue; } #submenus { backgr ...

Learning to implement a sliding effect on tab bar button click using Angular

When a user clicks on any tab button, I am using the transition effect "slide" to display the content. I have successfully implemented this in jQuery Mobile and you can see it in action in this fiddle: http://jsfiddle.net/ezanker/o9foej5L/1/. Now, I tried ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

Discover Headphones with Ionic

Is there a way to detect if headphones are connected to a mobile device (specifically an iPhone) using Ionic? Our Ionic app plays sound normally without headphones, but encounters issues when headphones are plugged in. When you start the app without headp ...

Building a DOM element using jQuery

I have a function $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); ...