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

An issue with modalInstance injection in AngularJS causing an error

MyAdmin.controller('AdminMasterController', ['$rootScope', '$q', '$scope', '$http', 'ApiCall', 'DTOptionsBuilder', 'DTColumnDefBuilder', '$window', 'myStorageSer ...

Utilize Meteor-tabular to effortlessly export data with convenient HTML5 export buttons

Currently, I am utilizing the tabular package to display data from a collection in a table format. However, when attempting to export the data using html5 export buttons with the button (csvhtml5), only the length of data visible in the table is exported, ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Determine if an object is empty in AngularJS

Is there a way to make a div element visible only after the user selects at least one checkbox? I attempted to achieve this using the following code within the div: <div class="col-md-1" ng-if="selectedElements.length > 0"> The variable selected ...

Issue with changing tabs in Angular UI bootstrap when using a button inside a tab

Is there a way to change the active tab using a button inside the uib-tabset directive? I've noticed that the button only seems to work when it's placed OUTSIDE the directive. Am I missing something here? Take a look at the code snippet below: ...

Tips for accurately dissecting a PDF document to determine the status of checkboxes

Looking for a solution to parse PDF forms on the server side, I have experimented with various node.js modules including pdf2json, hummus, and node-pdftk. While I have successfully retrieved all text fields, I am facing issues when it comes to extracting c ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

The error message "element.getAttribute is not defined" is common when using the Perfect

I'm facing an issue while trying to implement the perfect-scrollbar plugin on my AngularJS website. The error I encounter is as follows: TypeError: element.getAttribute is not a function at getId (http://localhost/Myproject/js/lib/perfect-scrollb ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Link JSON filters to specific JSON nodes on the map

I have data representing nodes and links for a force directed graph. The links can have different numbers of connections between them, such as one, two, or three links: {"nodes": [{"id": "Michael Scott", "type": "boss"} ,{"id": "Jim Halpert", "t ...

What could be causing this code to keep looping?

This is my submission for a class project. The task given was: "Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a num ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

PHP not receiving POST information from $.ajax call

My JavaScript triggers a POST method when the datepicker loses focus, calling the script rent-fetch-pick-up-point.php. However, the PHP script gets stuck at the if-statement because it's not receiving the POST data. The datepicker is associated with a ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...

Introducing the First Angular Factory

It's high time for me to finally inject my first angular Factory . . . Here is the code I have: .factory('Debts', function($q, $scope){ return MA; }) .controller('Admin', function ($scope, Debts) { $scope.Debts = Deb ...

What is the best way to directly send a message from a panel to a page-mod's content script?

When working with a code snippet in a Firefox addon like the one below: var pagemod = PageMod({ include: ['*'], contentScriptFile: [data.url('content.js')] }); panel = require("sdk/panel").Panel({ width: 322, height: 427, ...

What is the best way to retrieve the initial cell from a row that the user is currently hovering over?

Is there a way to extract the first cell from a row when a user hovers over it and then clicks a specific key combination? (considering using jQuery) I have a table set up similarly where placing the mouse over a tr and pressing ctrl+c will copy the ID t ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...