Enhance AngularJS functionality by implementing a custom method to handle sorting within ng-click and ng-show

I am currently managing a set of table columns that can be sorted in ascending and descending order. Previously, the sorting logic was implemented within each ng-click and ng-show directive in the following way:

HTML

<a style="color:black" href="" ng-click="sortReverse = !sortReverse; changeSortType('id')">
  Group id
  <span ng-show="sortType == 'id' && !sortReverse" class="fa fa-caret-down"></span>
  <span ng-show="sortType == 'id' && sortReverse" class="fa fa-caret-up"></span>
</a></th>

CONTROLLER

  $scope.sortType = 'count';
  $scope.sortReverse = true;

  $scope.changeSortType = function (sortType){
    $scope.sortType = sortType;
  };

  $scope.itemSortValue = function (item) {
    return Service.sort(item, $scope.sortType)
  };

We now aim to streamline this process by implementing a method that achieves the same outcome, reducing the amount of code in the HTML.

Unfortunately, I have been struggling to figure out how to achieve this using AngularJS. I have attempted various approaches without success. While I have come across some suggestions online, they have not yielded the desired results. Could someone please provide guidance on the code implementation?

Answer №1

When working with the <a> element, make sure to remove the line sortReverse = !sortReverse; from the ng-click and instead add

$scope.sortReverse= !$scope.sortReverse
to the first line of the method changeSortType.

Additionally, for the ng-show functionality, create a new method as follows:

$scope.myMethod = function (id, reverse){
    return id && reverse;
  };

Lastly, update the HTML code to the following:

<span ng-show="myMethod('id',!sortReverse)" class="fa fa-caret-down"></span>
  <span ng-show="myMethod('id',sortReverse)" class="fa fa-caret-up"></span>

Answer №2

Give this code a try.

HTML

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>

<div ng-app="myApp" ng-controller="customersCtrl">
<div class="jumbotron bg-dark" style="border-radius: 0px; margin-bottom: 0px;">
        <h1 class="text-center" style="color:azure;">Table Sort</h1> 
</div>
 <table class="table table-dark table-striped">
    <thead>
      <tr>
        <th ng-click="orderByMe('Name')" style="cursor: pointer;">Name <i class="fa fa-sort-desc" style="font-size:15px;color: whitesmoke" ng-if=" toggleCursor == 'desc'"></i>  <i class="fa fa-sort-asc" ng-if=" toggleCursor == 'asc'"></i></th>
        <th style="cursor: pointer;">City </th>
        <th style="cursor: pointer;"> Country</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat=" data in myData  | orderBy:myOrderBy">
       <th>{{data.Name}}</th>
       <th>{{data.City}}</th>
       <th>{{data.Country}}</th>
      </tr>
    </tbody>
  </table>

</div>
</body>
</html>

JavaScript File

 var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.get("https://www.w3schools.com/angular/customers.php").then(function(response) {
            $scope.myData = response.data.records;
        });
        $scope.toggleCursor = 'desc';
        $scope.myOrderBy = 'Name';
        $scope.orderByMe = function(sort) {
             $scope.myOrderBy = sort;
             $scope.sortArray = $scope.myData.sort();
             if($scope.toggleCursor == 'desc')
                {
                    $scope.toggleCursor = 'asc';
                    $scope.myOrderBy = $scope.sortArray;
                }        
             else
             {
                 $scope.toggleCursor = 'desc';
                 $scope.myOrderBy =  $scope.sortArray.reverse();
             }
        }
    });

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 utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

When trying to run a jQuery function on click or load events, an error message stating that

When I have an .on(click) event triggering an ajax call, I want the same actions to occur when the page loads as well. My idea is to create a function that contains everything within the .on(click) event and trigger this function on page load. Although I ...

Retrieve the data from a Sequelize Promise without triggering its execution

Forgive me for asking, but I have a curious question. Imagine I have something as simple as this: let query = User.findAll({where: {name: 'something'}}) Is there a way to access the content of query? And when I say "content," I mean the part g ...

Strange actions observed in AJAX POST request

This code snippet functions perfectly when I set a breakpoint in the backend and allow the value to be zero before continuing with the rest of the code. However, if I don't set a breakpoint and let it run, the value will become 2 and cause a break in ...

Is there a way to arrange 7 fractions in an array using Java?

I'm facing a challenge and need assistance in identifying my errors to move forward. I am tasked with creating a program that executes specific instructions. The objective is to build a Java class named Fraction to represent a ratio of two integers. ...

Struggling with Angular Material not functioning properly? All features seem to be included

I am having trouble with my website being split into different parts. I have included the CSS inside the head tag and the JS in the body, but it is still not working properly. - setup and I have also tried the following: <html ng-app="StarterApp"> ...

Setting up the Webpack configuration for a React application to incorporate source maps from external React packages that are listed as dependencies

How can the webpack.config.js file generated by a default React app be modified to allow for debugging of *.jsx files from other React packages listed as dependencies? The goal is to leverage the source maps provided by dependencies in order to debug JSX ...

Antialiasing with Three.js appears to be malfunctioning specifically on iPhone 5 and iPhone 5s devices

As a newbie to three.js, I managed to finish my project successfully. To enhance the graphics quality, I decided to enable antialiasing. renderer = new THREE.WebGLRenderer( { antialias: true } ); Unfortunately, after enabling antialiasing on iPhone 5 and ...

"Getting Started with Redux/React - Implement logic to add a new item if it doesn't already

I'm attempting to insert a single item into my nested Redux state, but only if it does not already exist in the list. I'm specifically looking for a solution using Redux, as I want that added flavor to my code. Here is how my state is structure ...

Tips for effectively implementing a custom theme alongside a component library that utilizes Material UI without the need to apply it to every single component

What is the correct way to utilize a custom theme with a component lib that utilizes Material UI without wrapping every single component? import { createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme({ palette: { ...

Protractor encounters difficulties in Firefox and Internet Explorer browsers

Having trouble running tests with the protractor in Firefox Here's a test case that works fine in Chrome, but fails in Firefox and IE browsers. Sample Test File <html> <head> <title>automation test</title> ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

Removing an object in Three.js using scene.getObjectByName() method

When developing my game, I encountered a challenge. I'm loading 4 different buildings and creating 15 clones of each within a for loop. These clones are then added to an array called masterBuildingArray, which I iterate through using a forEach loop. T ...

Creating a new item in a list using AngularJS functions perfectly on JSfiddle, but encounters issues when attempted in Visual

This is my first experience with AngularJS. Interestingly, when I tested my code on JSFiddle it worked fine, but in Visual Studio it's causing issues. http://jsfiddle.net/Y3BJa/399/ Any assistance would be greatly appreciated. I have a predefined ...

Resolving a Form Group Challenge in Angular 9

Disclaimer: I am still learning about angular and TypeScript in general. My goal is to create an activation component that can submit a code directly to the service if it's included in the URL parameter query. If the code is not in the URL, then the ...

Challenges encountered when attempting to align faces within Three.JS stemming from the use of two distinct

I'm currently facing an issue with my three.js code. My goal is to align two objects by selecting two faces and rotating the second face (and object) to match the normal vector of the first object's selected face. Here is what I have so far: v ...

Introducing LightZAP v2.54 (silent update2), the revolutionary Lightbox custom plugin that seamlessly launches when the page loads using the designated tag name (#img1)

As I have the LightZAP plugin installed on my website as an alternative to Lightbox, I am looking to trigger it (to display an image gallery with a specific image) when the page loads using the following link: index.html#img1, if possible. I have come acr ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

Weird State / Unusual Effectiveness with NextJS Links

I'm encountering some unusual behavior in a personal project I'm working on. The project is a recipe website with buttons at the top that lead to different pages querying Firebase for recipe data. In the Index.js file, Firestore queries pass pro ...

I am having trouble having a select component populate with new child components while still maintaining its original value

So here's the situation. Let me simplify things for you. I'm in the process of developing an app that generates JSON queries to be sent to a server. The query-building components are structured in a nested manner: QueryContainer > QueryGroup ...