Arranging column orders in AngularJS tables

The code snippet provided below is intended for sorting table columns but it seems to be causing an error message:

Error: $injector:unpr Unknown Provider

Unknown provider: orderbyFilterProvider <-

View:

<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th><a href="" ng-click="reverse=!reverse;order('lname', reverse)">Lastname</a></th>
      <th><a href="" ng-click="reverse=!reverse;order('fname', reverse)">Firstname</a></th>
      <th><a href="" ng-click="reverse=!reverse;order('maxAge', reverse)">Age</a></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in filteredItems = (nameslist | orderBy:predicate)">
      <td>{{ item.lname }}</td>
      <td>{{ item.fname }}</td>
      <td>{{ item.maxAge }}</td>
    </tr>
  </tbody>
</table>

Ctrl:

//Retrieve data from REST API
$scope.nameslist = resService.getAll();

//sorting function
var orderby = $filter('orderby');

$scope.order = function (predicate, reverse) {
   $scope.nameslist = orderby($scope.nameslist, predicate, reverse);
};

/* default */
$scope.order('-maxAge', false);

resService:

...
return {
   getAll: function () {
      return requestService.name.query();
   },
...
}

Is there a way to modify the sorting function to resolve this issue?

Answer №1

Below are the steps I took:

Updated HTML document.

<body ng-controller="testCtrl">

    <table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th><a href="" ng-click="reverse=!reverse;predicate = 'lname'">Lastname</a></th>
      <th><a href="" ng-click="reverse=!reverse;predicate = 'fname'">Firstname</a></th>
      <th><a href="" ng-click="reverse=!reverse;predicate = 'maxAge '">Age</a></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in nameslist | orderBy:predicate:reverse">
      <td>{{ item.lname }}</td>
      <td>{{ item.fname }}</td>
      <td>{{ item.maxAge }}</td>
    </tr>
  </tbody>
</table>
</body>



app.controller("testCtrl",['$scope','$filter',function($scope,$filter){
        $scope.nameslist = [{maxAge :112,fname:'first1' ,MiddleName: 'middle1',lname:'last1'},
      {maxAge :15,fname:'first2' ,MiddleName: 'middle1',lname:'last1'},
      {maxAge :11,fname:'first3' ,MiddleName: 'middle2',lname:'last2'},
      {maxAge :14,fname:'first4' ,MiddleName: 'middle3',lname:'last1'}
      ];

No custom filter is required for this task.

For a working example, check out this Plunker link.

Answer №2

To reverse the order of a table using Angular's built-in orderBy filter, you can follow this example:

<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th><a href="" ng-click="order('lname')">Lastname</a></th>
      <th><a href="" ng-click="order('fname')">Firstname</a></th>
      <th><a href="" ng-click="order('maxAge')">Age</a></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in (nameslist | orderBy:predicate:reverse)">
      <td>{{ item.lname }}</td>
      <td>{{ item.fname }}</td>
      <td>{{ item.maxAge }}</td>
    </tr>
  </tbody>
</table>

Additionally, here is the order function to achieve the reverse sorting:

$scope.nameslist = [{maxAge :112,fname:'Amy' ,MiddleName: 'Sue',lname:'Test'},
  {maxAge :15,fname:'Chris' ,MiddleName: 'Deb',lname:'Something'},
  {maxAge :11,fname:'Sue' ,MiddleName: 'Amy',lname:'Abcd'},
  {maxAge :14,fname:'Debby' ,MiddleName: 'Chris',lname:'Try'}
  ];

//sort function
$scope.predicate = 'lname'; 
$scope.reverse = false;

$scope.order = function (filterBy) {
   if ($scope.predicate === filterBy) {
       $scope.reverse = !$scope.reverse;
   } else {
       $scope.reverse = false;
   }
    $scope.predicate = filterBy;
};

The logic revolves around passing an additional parameter true to the orderBy for reversing the order.

If you encounter errors, make sure your ng-repeat syntax is correct like below:

<tr ng-repeat="item in filteredItems = (nameslist | orderBy:predicate:reverse)">

The correct syntax should be:

<tr ng-repeat="item in (nameslist | orderBy:predicate:reverse)">

You can view a working example on Plunker at the following link:

http://plnkr.co/edit/JSoyoCkBwknlAggEwU59?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

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

Display a featherlightbox popup when the page loads

Well, here's the deal. I don't have any experience with wordpress php coding at all, but I can make basic adjustments using the wordpress admin. Now I've run into an issue. I tried to use the feather lightbox js, and below is a snippet of co ...

Using ng-repeater to create a ui-grid within ui-tabs

I have a simple user interface tab with a grid, but when I switch tabs, the page needs to be scrolled in order to see the table. <uib-tabset class="tab-container tabbable-line"> <uib-tab ng-repeat="user in vm.users" heading="{{user.user.fullN ...

Tips for making sure your published npm package respects the baseUrl specified in the tsconfig.json file

I am currently developing an npm library using TypeScript. Within our project configuration, we have specified a baseUrl in our tsconfig.json file. "baseUrl": "src", When referencing files within the src directory, we can simply use: src |-folderA ...

Asking for access to a Node server with React authentication

Let me outline the current scenario: I am working with a database that contains registered usernames and passwords. My task at hand is to create a login form where users can input their username and password to log in. These credentials are already stored ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

What could be the reason for the "begin" script failing to execute?

I have a simple node and express application that works as expected, but I encounter an issue when trying to run the server from the script. When my script is set to "start", running the command simply opens my cmd. However, if my script is set to any oth ...

Troubleshooting NodeJS with Socket.IO 1.0: Identifying Memory Leaks Beyond the Heap

We have encountered an issue while trying to deploy a small NodeJS app with Socket.IO. The problem arises when the total memory usage (rss) exceeds 2gb after approximately 2 hours, despite the heap size being within acceptable limits. To confirm that the ...

When employing Flatlist, an issue arises where the image fails to appear on the screen, accompanied by an error message stating "value for uri cannot be cast from Double to String."

I'm facing an issue with displaying images in my flatlist. The error message I receive is "Error while updating property 'src' of a view managed by : RTCImageView." Can anyone help me identify what might be causing this problem in my code? ...

What is the best way to submit complex form data as an array or object?

I am consolidating passenger information by using input names in this format: passenger[1][name] passenger[1][surname] passenger[1][idnumber] passenger[2][name] passenger[2][surname] passenger[2][idnumber] However, when I submit the data in this way, the ...

What is the best way to randomly choose a string from an array and store it in a variable?

For instance var names = array["bob","tom","jake"]; Is there a way to choose a random name from the array and then set it as the value of a variable? var randomName = I'm not sure what code belongs here ...

Waiting for a response is not the same as waiting for firebase batches functions

There's a simple function that sets the loader value to true and then, when the function finishes, it sets it back to false. However, I'm facing an issue where my async/await functions are not properly awaiting the code that involves firebase bat ...

Button click event not triggering JavaScript execution

I am experimenting with HTML, PHP and JS and have encountered a problem. Here is my code: <html> <head> <title> Dummy Code </title> <script> sendMail(){ <?php $to = '<a href="/cdn-cgi/l/email-protection" class ...

Tips for Disabling Alert Pop-ups when Launching Desktop Applications from a Browser

Is there a way to prevent the alert pop-up when launching a desktop application from a web browser? For instance, when typing calculator:// in the browser, we want to eliminate the alert box using an Angular TypeScript file. see image reference ...

Deciding the optimal time to start a new JavaScript file and effectively organizing source code

Embarking on a substantial map application project involving approximately 5,000 lines of JavaScript, I am contemplating changing my approach to file organization. Traditionally, I would consolidate all code into a single file named 'main.js', bu ...

The jQuery attribute selector seems to be malfunctioning when targeting data attributes

Although this question may resemble others on SO like Selecting element by data attribute and jQuery how to find an element based on a data-attribute value?, I am still struggling to select all elements where the attribute "data-value" exists. The Issue ...

Exploring the Relationship Between jQuery and JSON through Iterating Over JSON Arrays

There is an array stored in a database: a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";} To manipulate this array, I first unserialize it using PHP and then encode it with JSON. The code snippet is as follows: $unwp = unserialize(&apos ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Suggestions for updating ng-repeat variable with autocomplete functionality?

Many thanks to the Stack Overflow community for helping me resolve my previous angularjs and autocomplete issue. Here is the link to the question: Angularjs with jquery auto complete not working However, I am facing a similar problem now within the ng-rep ...

Showing a specific document from an <input> field using AngularJS

I currently have a functional example using standard Javascript, but I am eager to enhance its compatibility with AngularJS. My main objective is to dynamically update the span element with the filename of the file chosen by the user. Below is the code s ...