Sorting Angular components in reverse alphabetical order from A to Z

I feel like the answer to this problem is staring me right in the face, but no matter how hard I look, I just can't seem to find it.

When dealing with a large ng-repeat, I have multiple sort options that I pass as an array. The user has the ability to choose how they want the data sorted.

Sorting from A-Z works perfectly fine, but for some reason sorting from Z-A is not functioning as expected.

Check out this interactive demonstration on Fiddle http://jsfiddle.net/Tk39P/4/

The code I am using is very similar to what I've successfully implemented in other Angular applications:

return -result.whatever;

So, where did I make a mistake? :) Thanks!

Answer №1

Update your code snippet as shown below: $scope.orderBy = 'price-low-high'; $scope.predicate='price'; $scope.reverse=true;

    $scope.orderByOptions = function (result) {
        if ($scope.orderBy == 'price-high-low') {
            $scope.predicate='price';
            $scope.reverse=false;

        }
        else if ($scope.orderBy == 'letter-az') {
            $scope.predicate='letter';
            $scope.reverse=false;

        }
        else if ($scope.orderBy == 'letter-za') {
            $scope.predicate='letter';
            $scope.reverse=true;

        }
        else
        {
            $scope.predicate='price';
            $scope.reverse=true;
        }


    };    

HTML Change data-ng-change="orderByOptions()"

  <select data-ng-change="orderByOptions()" class="order-by" data-ng-model="orderBy" id="orderBy" data-ng-show="results.length > 0">

View the JSFiddle example

You may also consult this documentation on AngularJS orderBy

Answer №2

One issue arises when the variable result.letter contains a non-empty string,

-result.letter

this will result in NaN.

To solve this problem, you can utilize the following:

-result.letter.charCodeAt(0);

Check out the demo here

Answer №3

When dealing with sorting strings using the orderBy function, it's recommended to utilize the third argument, reverse. This is especially useful when the concept of returning a negative string doesn't apply. If you are working with single alphabet, single case letters, you could potentially use "Z".charCodeAt(0)-string.charCodeAt(index), but this method may not be visually ideal if your string is not a single letter.

To implement this, simply watch the orderBy value and assign a scope variable like $scope.reverse based on it. Then, incorporate it in your code as shown below:

<li data-ng-repeat="result in results
    | orderBy: [orderByOptions, orderByPriceLowToHigh]:reverse track by $index">

For a live demonstration, check out the Fiddle here: http://jsfiddle.net/C3BFf/

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

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Multiple jQuery AJAX requests triggered in a click event handler

I am in the process of developing a PHP web application and utilizing the datatables jQuery plugin along with jQuery AJAX calls to create a dynamic table for editing, deleting, and adding elements. Although it appears to be working correctly, I've not ...

JavaScript: what is the method to add a paragraph when the condition is not met?

I am currently working on a project that involves checking if a student is actively engaged in an online journal. This is done by tracking the student's progress using a unique userId. If the student's userId is not found in the JSON data returne ...

Using AngularJS to add a third-party module called ngIdle

Below is a controller that I am working with: (function () { "use strict"; var app = angular.module('Demo') .controller('MainController', ['$rootScope', '$scope', '$location', 'curUser',MainC ...

What are some ways to optimize the use of the jquery.mCustomScrollbar.js script?

I have a myriad of inquiries and would greatly appreciate your assistance in addressing them. Despite spending countless hours attempting to solve the issue independently, I have been unsuccessful. One question that plagues me is why, when using Google Ch ...

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...

Seeking help with the conversion of jQuery code to Angular

A table on our website is dynamically populated using jQuery ajax. Here is the code snippet responsible for this functionality: $.ajax({ type: "POST", cache: false, url: "/files/event_lister.php", // script that fetches data from ...

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

What is the best way to conceal my class element if the data-reviews number is under 5?

I have been experimenting with basic JavaScript for the data-reviews="2" scenario and it worked successfully. However, what I am aiming for is to hide the entire <span> section when the value of data-reviews is less than 5 or any specific ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

What is the best way to transfer data from Vue.js to a PHP variable?

<section class="scans"> <h3>Scans</h3> <ul v-if="scans.length === 0"> <li class="empty">No scans yet</li> </ul> <transition-group name="scans" tag="ul"> <li v-for ...

group array by month and year

I have an array structured like this var dataset = [[1411151400000,1686],[1428604200000,1686],[1411151400000,1686]....] The goal is to group the data based on months and calculate the total sum of values for each month. The expected final output should ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

Tips for displaying a placeholder image within the Next.js image component

I am currently facing an issue with displaying images from API calls. To handle situations where there are no images or errors, I have implemented a code snippet which includes a placeholder image. However, the implementation seems to not be functioning as ...