AngularJS: Implementing sorting and reverse-sort functionality on a table with a header generated using ng-repeat in AngularJS

I have this HTML section below. I am using ng-repeat to populate a table with data and I'm looking for a way to sort and reverse-sort the data by clicking on the table columns. I attempted a solution but all columns are accessing the same property.

<div>
<table class="friends">
    <tr>
        <th ng-repeat="key in keys" ng-click="sortBy(propertyName)">{{key}}</th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
        <td ng-repeat="key in keys">{{friend[key]}}</td>
    </tr>
</table>

This is how my Controller looks like:

var friends = [
    {name: 'John', phone: '555-1212', age: 10},
    {name: 'Mary', phone: '555-9876', age: 19},
    {name: 'Mike', phone: '555-4321', age: 21},
    {name: 'Adam', phone: '555-5678', age: 35},
    {name: 'Julie', phone: '555-8765', age: 29}
];
$scope.keys = {
    first: "name",
    second: "phone",
    third: "age"
};


$scope.propertyName = 'age';
$scope.reverse = true;
$scope.friends = friends;

$scope.sortBy = function(propertyName) {
    $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
    $scope.propertyName = propertyName;
};

Answer №1

Your code needed a slight update. Instead of passing the property name in ng-click, you need to pass the key.

Check out the updated working code here: http://jsfiddle.net/halirgb/Lvc0u55v/

Here is the modified line:

 <th ng-repeat="key in keys" ng-click="sortBy(key)">{{key}}</th>

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

Utilizing the Hebrew calendar with the FullCalendar library

Looking to incorporate the Hebrew calendar into the FullCalendar library. Is there a built-in way to achieve this within the library's existing functions? library If not, what is the manual process for integrating the Hebrew calendar? Appreciate any ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

Show the fadeIn effect only one time during a session

I'm dealing with a situation where I have created a function like so: function loremIpsum() { $('.element').fadeIn() } The problem arises when a user can go back and trigger the loremIpsum() function again using a second button, but I want ...

Tips for presenting styled HTML content within a dynamic list using HTML and JavaScript

Is there a way to display HTML formatted text within a dynamic list in HTML? I've tried implementing it, but the tags are being displayed instead of the formatted text. Here's an example of the code: <!DOCTYPE html> <html> <body> ...

Harnessing the power of custom directives in HTML

I have developed a custom directive that adds the active class to the clicked li element in the menu list based on the URL. .directive('addActive', [function() { return{ ... link : function(scope, element, attrs){ ...

Setting a scope variable in an isolate scope from a link function can be achieved by accessing the

In my attempt to assign a variable within an isolate scope, I am encountering difficulties accessing the variable set in the linked function. Surprisingly, I can access the controller's variable without any issues. app.directive('myDir', fu ...

Unable to retrieve coverage report using rewire and cross-env

My challenge lies in obtaining the coverage report using nyc, which works flawlessly without the cross-env plugin. cross-env NODE_ENV=test nyc mocha --ui bdd --reporter spec --colors --require babel-core/register tests --recursive When executing this com ...

The hamburger menu is only functional for a single link

I've been developing a hamburger menu for my website, and it seems to be working fine until I click on a link. Once I navigate to a new page, the menu stops responding. To fix this issue, I attempted to use window.location.reload, which worked in Chro ...

Botkit corner flaw

I'm having trouble updating a dependent package included in Botkit. When I run npm install on the package.json provided below, Npm alerts me that the hoek package is vulnerable. I attempted to resolve this by running npm audit fix but it did not wor ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Creating a personalized filter list in Vue Instant Search: A step-by-step guide

Currently, I'm utilizing Laravel Scout with Algolia as the driver. Vue is being used on the front end and I've experimented with the Vue instant search package, which has proven to be very effective. The challenge I am encountering involves cust ...

Issue encountered while installing semantic-ui-react and semantic-ui-css with React using npm

Issue encountered during the semantic UI installation via npm install Any solutions for this problem? ...

Adjust the input values based on the child elements within the main container

Here is a series of DIVs with unique IDs: <div id="2988"> <div class="site">YaHoot.com</div> <div class="logo">/images/yahootLogo.jpg</div> //[and so on] <input type="button" value="YaHoot" onclick="javascript: ...

How to handle custom errors in ASP.NET WebApi 5 by throwing HttpResponseException with incorrect status code

When using WebAPI / REST, you have the ability to send personalized error messages along with a standard Status Code. For example, you can send a 402 - Not found status code along with your own message in the header or body. This feature works perfectly f ...

Node.js: The object in req is not functioning as expected

// Function to merge objects with unsent columns kept from old objects. function merge_options(obj1, obj2) { const obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname] ...

Tips for creating a React Table where one element spans the entire cell

Hello, I am trying to make my td element tag occupy the entire cell belonging to that column. The current output I have is shown in this screenshot: https://i.sstatic.net/erPJC.png Essentially, I want the "Independent Study" to take up the first column. H ...

I encounter difficulties when retrieving data in Next.js

Within a Next.js project, there is code provided that retrieves data from an external API endpoint and then passes it as props to a component called Services. This Services component utilizes the received data to dynamically render different sections of th ...

Is there a way to make my JavaScript code function within an ASP.NET CSHTML file?

I am working on a web project where I have an HTML input for uploading a picture to my FTP server. I want to use JavaScript to detect changes on my upload button. This is the code in my CSHTML file: @using (Html.BeginForm("UploadFile", "Upload", For ...

Set up a Bootstrap date picker to populate two input boxes with a start and end date. Additionally, disable the ability for the date value to change

In my project, I have implemented Bootstrap Datepicker to set two input boxes for selecting start and end dates. The rule is that the start date must be after today and the end date must be after the selected start date. To disable specific dates in the da ...