Tips for organizing a list in Angular 1 when a button is clicked

I'm looking for help with sorting a list in Angular 1 when a button is clicked. I want the ability to toggle between ascending and descending order on each click. Here is a link to the code: https://plnkr.co/edit/HYuk7DAgOY6baWhrvXko?p=preview

var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope) {
      vm =this;
      $scope.name = 'World';
       $scope.sortDir = "ASC"
     $scope.customerData= [
      {
        "name":"naveen",
        "Location":"Delhi",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abc5caddcecec585c5d8c2df9392ebccc6cac2c785c8c4c6">[email protected]</a>"
      },
      {
        "name":"sss",
        "Location":"Delhi",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365857405353581858455f420e0f76515b575f5a1855595b">[email protected]</a>"
      },
      {
        "name":"aa",
        "Location":"Delhi",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb2bdaab9b9b2f2b2afb5a8e4e59cbbb1bdb5b0f2bfb3b1">[email protected]</a>"
      },
      {
        "name":"zzz",
        "Location":"Delhi",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e987889f8c8c87c7879a809dd1d0a98e84888085c78a8684">[email protected]</a>"
      }
    ]

    $scope.sortButtonClick =function(){
         $scope.sortDir = "DESC"

    }
    });

Answer №1

To sort the data, you can use a filter called orderBy:

  $scope.sortButtonClick = function() {
    if($scope.sortDir === "ASC"){
    $scope.sortDir = "DESC"
    $scope.customerData = $filter('orderBy')($scope.customerData, '-name');
    }else{
    $scope.sortDir = "ASC"
    $scope.customerData = $filter('orderBy')($scope.customerData, 'name');

    }
  }

DEMO

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $filter) {
  vm = this;
  $scope.name = 'World';
  $scope.sortDir = "ASC"
  $scope.customerData = [{
    "name": "naveen",
    "Location": "Delhi",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e707f687b7b7030706d776a26275e79737f7772307d7173">[email protected]</a>"
  }, {
    "name": "sss",
    "Location": "Delhi",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3cdc2d5c6c6cd8dcdd0cad79b9ae3c4cec2cacf8dc0ccce">[email protected]</a>"
  }, {
    "name": "aa",
    "Location": "Delhi",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94faf5e2f1f1fabafae7fde0acadd4f3f9f5fdf8baf7fbf9">[email protected]</a>"
  }, {
    "name": "zzz",
    "Location": "Delhi",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b7b8afbcbcb7f7b7aab0ade1e099beb4b8b0b5f7bab6b4">[email protected]</a>"
  }]
  $scope.sortButtonClick = function() {
    if($scope.sortDir === "ASC"){
    $scope.sortDir = "DESC"
    $scope.customerData = $filter('orderBy')($scope.customerData, '-name');
    }else{
    $scope.sortDir = "ASC"
    $scope.customerData = $filter('orderBy')($scope.customerData, 'name');

    }
  }
});
<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f3fcf5e7fef3e0bcf8e1d2a3bca6bcea">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl">
        <button ng-click="sortButtonClick()">{{sortDir}}</button>
     <ul style="margin: 40px;">
        <li ng-repeat="item in customerData ">
            <span>{{item.name}}</span>
            <button ng-click="deleteItem(item)">X</button>
        </li>
    </ul>
  </body>
</html>

Answer №2

HTML

 <ul ng-repeat="obj in data | orderBy:property:reverse">
            <li>{{obj.name}}</li>
            <button ng-click="removeItem(obj)">X</button>
        </ul>

Controller

$scope.property = 'name';

$scope.reverse = true;

$scope.toggleSortOrder =function(){
    $scope.reverse = !$scope.reverse 
}

Demo

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

Unsupported file format for Three.js FBX Binary model

I am currently working with three.js in a mobile application that is built using JavaScript. I am trying to incorporate a 3D model using an .fbx file, but I am facing issues with the binary format not being supported by FBXLoader. As someone who doesn&apos ...

Merge $FirebaseObject with multiple location updates

Is there a method for performing a multi-location update with a $FirebaseObject? My attempt results in an error message "Firebase.update failed: First argument contains an invalid key ($id) in property" var customerData = {}; customerData["Customers/" + ...

Using V-model in conjunction with the boostrap-vue b-table component

I am attempting to bind v-model by passing the value inside the items array. However, the binding is not functioning correctly. The main objective here is to utilize a store since all these values are utilized across multiple "wizard" components. Whe ...

Is there a way for me to retrieve the information within this function? It seems like it may be a promise, but I am uncertain

I need help extracting the data from doc.data and sending it to another component based on the dropdown selection. It appears that the data is in promise format, and despite trying async/await, I am struggling to access it. Can anyone guide me on how to ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

Uploading profile images with AngularJS and Firebase

I am encountering an issue with my JavaScript image uploader. It successfully uploads an image and provides the image src, but I need to save this value in my FireBase DB for the current user that is being created. Initially, I attempted to output the img ...

Adjusting the content of a single text box by typing in another

Is it feasible to automatically convert a Nepali date input in one textbox into an English date and display it in another textbox without any page refresh? I have a PHP function that can translate dates between Nepali and English, and I want it to execute ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Transforming items into an array

Creating a JSON object with the following structure is something I'm trying to accomplish: { "PROMO": { "ID": 1, "NAME": "PROMO ONE", "BUNDLES": { "0": { "BUNDLE": { ...

Issue with webcomponents-lite.js file

Encountering this particular error message in the console while attempting to run the application: webcomponents-lite.js:64Uncaught TypeError: Cannot read property 'getAttribute' of null at webcomponents-lite.js:64 at Object.549 (webcomp ...

Issues with integrating React-Bootstrap onto components

Just started working on a new React application and decided to incorporate react-bootstrap. After running npm install react-bootstrap bootstrap, I noticed that the Column, Row, and Button tags were not functioning properly even though the react-bootstrap ...

Exploring the world of XD plugins, utilizing npm packages and Node.js APIs

Is it feasible to integrate npm packages and Node.js APIs into my Adobe XD plugin development process? ...

React's `setState` function seems to be failing to hold onto

Recently, I've been challenged with creating an infinite scroll loader component. However, I'm facing a peculiar issue where my 'items' array is constantly resetting to [] (empty) instead of appending the new results as intended. A cou ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Executing a long job in PHP (Laravel) while simultaneously making an AJAX call

Looking to create a real-time progressing bar? I attempted to incorporate this example into my Laravel project but seem to have missed a step. Here is my HTML and JavaScript code: <div style="border:1px solid black;width:500px;height:80px"> &l ...

Guide on incorporating an HTML element within a binding in Nuxt or Vue

I'm struggling with adding an HTML element <br /> inside a data bind. I want to modify the text "I like playing games" to include a line break, making it read as "I like playing <br /> games", but I can't seem to get it right within t ...

What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any gri ...

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...

Employing an array for transmitting parameters to a function

I am wondering about the structure of my code which includes variables x_1, x_2, x_3, …., x_n being passed in an array. Here is how it looks: var x_1 = "something"; var x_2 = "something"; var x_3 = "something"; . . . var x_n = "something"; var parameter ...

Guide to extracting the value of an attribute from a Meteor collection object

In my database, I have a collection called Meteor.users. Each user in this collection has an attribute named “lastQuestionAnswered”, which stores the questionId of the last question they answered. { "_id" : "jrCJiuo7eprNFKfLG", "name" : "Elon Musk", " ...