Organizing data in a table with AngularJS

I have recently started learning AngularJS and am currently working on sorting my table by clicking on the table headers. When a header is clicked, I want the rows to be sorted based on that specific header.

If you'd like to see my code in action, here is the plnkr link: http://plnkr.co/edit/mbTq5865KKNzlvpJJy1l

Below is the relevant code snippet:

$scope.setRepoSortOrder = function(order) {
      if ($scope.repoSortOrder === order) {
        if ($scope.repoSortOrder.charAt(0) === '+') {
          order = order.replace('+', '-');
        } else {
          order = order.replace('-', '+');
        }
      }
      $scope.repoSortOrder = order;
    };

This is how my table structure looks:

<table>
    <thead>
        <tr>
            <th><a href="" ng-click="setRepoSortOrder('-name')">Name</a></th>
            <th><a href="" ng-click="setRepoSortOrder('+stargazers_count')">Stars</a></th>
            <th><a href="" ng-click="setRepoSortOrder('-language')">Language</a></th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="repo in repos | orderBy:repoSortOrder">
            <td>{{repo.name}}</td>
            <td>{{repo.stargazers_count | number}}</td>
            <td>{{repo.language}}</td>
        </tr>
    </tbody>
</table>

By clicking on the table headers for 'Name', 'Stars', or 'Language', you can sort the rows accordingly. Additionally, clicking on a header multiple times will change the sorting from ascending to descending order.

Initially, 'Name' and 'Language' columns are sorted in ascending order, while 'Stars' column is sorted in descending order.

I've implemented this functionality myself, but I'm open to feedback and suggestions on improving it, especially from those experienced with AngularJS. Please take a look at the plnkr link and let me know your thoughts.

Thank you for any input!

Answer №1

To enhance performance, consider incorporating a reverse flag with the orderBy filter as shown below:

$scope.repoSortOrder = "-stargazers_count";
$scope.isReverse = false;

$scope.setRepoSortOrder = function(order) {
  $scope.isReverse = ($scope.repoSortOrder === order) ? !$scope.isReverse : false;
  $scope.repoSortOrder = order;
};

For demonstration, check out this Example Plunker: http://plnkr.co/edit/CM1BGkQc0AYbrraAPq8r?p=preview

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

Why is my "webpack" version "^5.70.0" having trouble processing jpg files?

Having trouble loading a jpg file on the Homepage of my app: import cad from './CAD/untitled.106.jpg' Encountering this error message repeatedly: assets by status 2 MiB [cached] 1 asset cached modules 2.41 MiB (javascript) 937 bytes (rjavascript ...

Issue with fetching data from Vuex in VueJS doesn't give expected result

I'm currently working on integrating a messaging/alert system using Vuex in my project. The goal is to pass an argument from various components, triggering the display of specific messages through vuex getters. However, I'm facing an issue where ...

In order to avoid errors, it is necessary to enclose "RawText "; }"" within an explicit <

Just started working with React and encountered this error message: The RawText "; }" needs to be wrapped in a specific tag Everytime I attempt to map my JSON array, this error pops up. I've heard it might be related to space characters, but I ca ...

How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows: "marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } } I want to display the re ...

Delay the loading of templates when utilizing ng-controller

I am trying to delay the loading of my main controller/template (AppController) until I fetch the user's profile from a service. For all navigation routes, I am using $routeProvider with resolve. .when('/edit/:editId', { te ...

Please tap to dial: Access to navigation is restricted

Trying to add a click-to-call link with the following code: <a href="tel:+4912345678912">Tel: +4912345678912</a> Despite Google developers saying it should work, major mobile browsers are blocking the navigation when clicking on the link. It ...

Transferring information between pages through ajax communication

I am working with two pages named testing.php and submission.php. My goal is to send data from testing.php to be displayed on submission.php. For example, when a user clicks on test1, they should be directed to submission.php where I want to display the te ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

Utilizing Nested JSON for Stacked Highcharts Implementation

I've been researching extensively about nested json for Highcharts stacked percentage column, but I haven't been able to get the desired output. Below is the code that I have tried, but unfortunately it's not producing the expected result. ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Looking for assistance with regards to submitting an event

I have been working on developing a form and validating it using jQuery before submitting it to the server. Everything seems to be functioning correctly except for the function on the submit event. The form is being submitted with errors and upon checking ...

Preventing Multiple Form Submissions in JavaScript

I'm having an issue with my form submission to Parse where, after adding client-side validation, the data is being double submitted to the database. Despite adjusting my code based on other Stack posts and being new to JavaScript, I'm still expe ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

Retrieve asynchronous JSON settings before loading the AngularJS submodule library

I am dealing with a distributed AngularJs library module that is utilized in various other AngularJs applications which are out of my control. In my research, I have discovered that it is possible to load JSON settings for an AngularJs application via an ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

Invoking a function using an identifier for modification

I am currently developing a solution, and here is my progress so far: http://jsfiddle.net/k5rh3du0/ My goal is to invoke a function using both the onLoad and onerror attributes with an image. <img src="http://www.etreeblog.com/favicon.ic0" alt="status ...

Enhancing Filtering Capabilities with Multiple ng-Model in AngularJS

I am facing an issue with filtering a form based on user input in a text box or selection from a dropdown list. The text box filter works fine individually, but when I try to combine it with the dropdown list selection, neither filter seems to work. Below ...

Troubleshooting encoding problems with Google Cloud's Speech-to-Text API using Node.js

I'm currently working on a project that involves capturing audio from a user's microphone and sending it to a server for translation using Google's Speech-to-Text API. I am utilizing navigator.mediaDevices.getUserMedia() to access the audio, ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...