How to sort data in AngularJS by clicking on a column to change the order from ascending to

The code view below is what I am currently working with:

<tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>

I am looking to dynamically change the orderBy parameter when a column is clicked. For example, if a user clicks on the location column, I want the orderBy condition to switch to 'location' instead of 'code'. The updated form should look like this:

<tr ng-repeat="c in clients | orderBy:'location'">

Answer №1

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.prefix = '-';
  $scope.order = '';
  $scope.sortData = function(type) {
    $scope.prefix = $scope.prefix === '-' ? '+' : '-';
    $scope.order = $scope.prefix + type;
  }
  $scope.arrowDirection = function(type){
    if($scope.order.indexOf(type) !== -1)
      return $scope.prefix === '+' ? '↑' : '↓';
    return '';
  }

  $scope.items = [
    { name: 'Alice', age: 28 },
    { name: 'Bob', age: 35 },
    { name: 'Eve', age: 22 },
    { name: 'Dan', age: 31 },
    { name: 'Grace', age: 40 }
  ]
})
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
th{
  cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>      
      <th ng-click='sortData("name")'>Name {{arrowDirection("name")}}</th>
      <th ng-click='sortData("age")'>Age {{arrowDirection("age")}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in items | orderBy:order">
      <td>{{item.name}}</td>
      <td>{{item.age}}</td>
    </tr>
  </tbody>
</table>

Answer №2

Implement datatables.js to simplify sorting tasks Access the CSS file for datatables.js here

Download the JavaScript file for datatables.js here

Answer №3

To implement sorting on the column, use ng-click and call a function named setSortByParameter to set the parameter sortBy.

Now, include the following code for orderBy:

<tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">

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 of req.file being undefined when using Multer in Node.js with Express Router

I have been working on incorporating File Upload capability utilizing multer and Express Router. I set up an endpoint /batch_upload using router.use in the following manner: api.js router.use( "/batch_upload", upload.single("emp_csv_data"), userCo ...

Easily validating forms using javascript

I'm attempting to design a basic HTML form and would like to implement javascript for validating the input values. Below is the form tag: <form action="" onSubmit="return formValidation();" method="Post" name="form"> Here is a section of the ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Steps to adding a collection of links (stylesheets, javascript files) to each html document

Is it feasible to add a list of links to multiple HTML files? I was inspired by W3 School's W3 Include functionality, which allows you to import blocks of HTML code into various files simultaneously, making it convenient for making changes across many ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

Guide to using JavaScript to multiply the values from two text fields and showing the result in a separate text field

Here is the code that I am currently using: <script type="text/javascript"> $(function() { $("#addAll2").click(function() { var add = 0; $("#discount") = $dis $(".amt2").each(function() { ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...

Utilize SCSS values within TypeScript by applying them on a class level

let changeClassDisplay = document.getElementsByClassName('sidebar'); for (var i = 0; i < changeClassDisplay.length; i += 1) { changeClassDisplay[i].style.display = 'block'; } I encountered an issue with this code whe ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

Transitioning from traditional Three.js written in vanilla JavaScript to React Three Fiber involves a shift in

I am currently faced with the task of converting a vanilla JS Three.js script to React Three Fiber. import * as THREE from 'three'; let scene, camera, renderer; //Canvas const canvas = document.querySelector('canvas') //Number of lin ...

When trying to apply styles using ng-style attribute with jQuery, Angular does not seem to

Check out this plunker showcasing the issue : http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm Take a look at the code : var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { console.log('yeah'); ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

Obtaining Position Coordinates of an Element Linked to an Object in AngularJS $scope

Imagine a website with a left column containing filters like checkboxes and text fields. The main column displays items that are filtered based on the values provided in the left column. When a user changes a value in the filter column, a small floating el ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Finding the length of a filter in an AngularJS directive

I'm trying to figure out how to retrieve the value of filtered.length within my custom directive called my-dir. <li my-dir ng-repeat="result in filtered = (results | filter:query | orderBy: 'title')"> <h1>{{ result.title }}& ...

Exploring the Art of Programming SVG

I am thinking about creating a website that is similar to stackoverflow, but with the added feature of allowing answers to include drawings such as schematics. I would like to have a section in the answer form where users can create these schematics with ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...

Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an ...