Issue with Angular JS orderBy when sorting by numerical fields is not functioning as expected

Within my controller, I implemented code to convert the rank into a Float data type.

details.rank = '';
$scope.order = function (predicate) {
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
    if (predicate == 'rank') {
        for (var i = 0; i < data.countries[$scope.index].cities.length; i++) {
            details.rank = parseFloat(data.countries[$scope.index].cities[i].rank);
        }
        $scope.predicate = predicate;
    } else $scope.predicate = predicate;
};

However, an error is arising stating that ReferenceError: details is not defined

The json structure in use is as follows:

{
    "countries": [{
        "country": "India",
        "cities": [{
            "name": "Bangalore",
            "rank": "40"
        }, {
            "name": "Kolkata",
            "rank": "54"
        }, {
            "name": "Mumbai",
            "rank": "32"
        }, {
            "name": "Chennai",
            "rank": "42"
        }]
    }, {
        "country": "China",
        "cities": [{
            "name": "Guangzhou",
            "rank": "111"
        }, {
            "name": "Beijing",
            "rank": "90"
        }, {
            "name": "Fuzhou",
            "rank": "21"
        }, {
            "name": "Baotou",
            "rank": "23"
        }]
    }]
}

In the html file, there should be functionality where clicking on the table header allows sorting of the table in both ascending and descending order, which currently seems challenging to implement.

<th>
    <a href="" ng-click="order('rank')">RANK</a>
    <span ng-show="predicate === 'rank'" ng-class="{reverse:reverse}">     </span>
</th>
<ul ng-repeat="city in countryType">
    <li ng-repeat="details in city.data.cities | orderBy:predicate:reverse">
        <div class="text" id="t1"> {{details.name}} </div>
        <div class="text" id="t2"> {{details.rank}}</div>
        <div class="text" id="t3"> {{details.population}} </div>
        <div class="text" id="t4"> {{details.language}}</div>
    </li>
</ul>

Answer №1

If you want to create a dynamic sorting feature by clicking on the header divs, you can achieve it like this:

<ul ng-repeat="city in countryType">
    <li>
        <div class="text" ng-click="orderListBy('name')"> Name </div>
        <div class="text" ng-click="orderListBy('rank')"> Rank</div>
        <div class="text" ng-click="orderListBy('population')"> Population </div>
        <div class="text" ng-click="orderListBy('language')"> Language</div>
    </li>
    <li ng-repeat="details in city.data.cities | orderBy:predicate:reverse">
        <div class="text" id="t1-{{$index}}"> {{details.name}} </div>
        <div class="text" id="t2-{{$index}}"> {{details.rank}}</div>
        <div class="text" id="t3-{{$index}}"> {{details.population}} </div>
        <div class="text" id="t4-{{$index}}"> {{details.language}}</div>
    </li>
</ul>

Make sure to include the following code in your controller:

//initialize values
$scope.predicate = 'rank';
$scope.reverse = false;

$scope.orderListBy = function(attr){
    $scope.predicate = attr;
    $scope.reverse = !$scope.reverse;
};

This implementation will toggle the sort order when clicking repeatedly on a column header.

Note: Remember to use unique IDs within the ng-repeat directive to prevent errors and maintain valid HTML markup.

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

Responsive Website with Horizontal Scrolling

Is it feasible to develop a website that smoothly scrolls across five panels horizontally while maintaining responsiveness? I've managed to achieve this for a specific viewport size by nesting a div with the five panels extended and using javascript t ...

Mastering the art of simultaneously running multiple animations

Utilizing two functions to apply a Fade In/Fade Out effect on an element. Confident in the functionality of both functions, as testing them sequentially in the Console proves their effectiveness. However, executing: fadeIn() fadeOut() seems to result in ...

Blip Scripts: Converting JSON to JavaScript - Dealing with Undefined Arrays

I am currently working on a project to develop a bot on Blip. There are certain parts where I need to send a request to an API and then use a JavaScript script to extract elements from the JSON response. The JSON response I received from the API is stored ...

Has anyone discovered an Angular2 equivalent to $provide.value() while testing promises?

I am currently experimenting with testing a promise in Angular2. Here is what I have so far: this.fooService.getData().then(data => this.fooData = data); If you are interested in learning about testing promises for Angular 1, check out this article. ...

How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement: Math.random() > 0.5 ? 'spikes' : 'slime' I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those th ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

"Vue Filepond: Enhancing Your Images with Cropping

Currently, I am integrating filepond with VueJS to facilitate image uploads. To enable image cropping during upload, a specific configuration is required. The filepond plugin has been globally registered, as shown below: import Vue from 'vue'; i ...

The mat-datepicker appears in a unique location each time it is opened

I am facing an issue with my mat-datepicker appearing in the opposite place when clicked on one component. How can I resolve this? I have two different components with mat-datepicker, but they behave differently. I suspect that imitating a click in one com ...

Ensure the date is displayed in the format of dd-mm-yyyy when using the input type=date

Here is the code I am currently using : <input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" max=<?php echo ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

Ensure that the text within the ng-repeat is wrapped in a span element and each

When using ng repeat in span, I encountered a word breaking into a new line. Here is the actual output: https://i.stack.imgur.com/k4c9k.png To style this, I implemented the following CSS: border: 1px solid #ECE9E6; border-radius: 3px; text- ...

Trouble with Angular localization module displaying codes instead of non-ASCII characters

I am currently utilizing a module from this source to facilitate localization efforts. However, I have encountered an issue where special characters are being displayed as their corresponding ASCII codes instead of their actual symbols. For example, &a ...

How to send data to Material-UI drawer components

In the component called Setup, there are input fields that each hold their own data stored in an object named dropdowns. Alongside each input field, there is a drawer component containing the ID of that specific input field. I have a function called handle ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

There was a rendering error: "Type Error: Unable to access the 'PAY_TYPE' property of null"

I am attempting to retrieve the PAY_TYPE value from the callback_details object by using JSON.parse() function to convert a string into an object. However, I keep encountering an error related to the question's title. Here is my code snippet: <td ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...

Loading a gallery dynamically using AJAX in a CakePHP application

I am currently working with Cakephp 2.8.0 and I am facing an issue with implementing ajax in my application. I have a list of categories displayed as li links, and upon clicking on a category, I need to remove certain html code, locate the necessary catego ...