How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data with each click, and I'm unsure how to handle both actions when they are stored in different variables using ng-repeat. Any assistance would be greatly appreciated!

    <!DOCTYPE html>
      <html lang="en" ng-app="frontendTest">
      <head>
        <title>Frontend Test</title>
        <meta charset="utf-8"/> 

        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <link rel="stylesheet" type="text/css" href="resources/bootstrap/dist/css/bootstrap.min.css"> 

        <script type="text/javascript" src="resources/angular/angular.min.js"></script>
        <script type="text/javascript" src="resources/angular/angular-route.min.js"></script>
        <script type="text/javascript" src="app.js" ></script>
        <script type="text/javascript" src="controller.js" ></script>
      </head>
      <body ng-controller="CountriesController as countries">

        <header>
          <h1>Frontend Test</h1>  
          <div></div>
        </header>

        <section class="buttons">
          <input type="button" value="Load Countries" ng-click="load()">
          <input type="button" value="Sort Countries" ng-click="sort()">
        </section>

        <table class="table">
          <thead>
            <tr>
              <th class="col-md-6">Name</th>
              <th class="col-md-6">Population</th>
            </tr> 
          </thead>
         <tbody>
           <tr ng-repeat="country in countries track by $index" >            
             <td class="col-sm-6">{{country.country}}</td>
             <td  class="col-sm-6">{{country.population}}</td>
           </tr>
         </tbody>
        </table>                        
      </body>
    </html>

angular
  .module("frontendTest",[])
  .controller("CountriesController", CountriesController);

  CountriesController.inject =['$scope'];

  function CountriesController($scope){

    $scope.data = 
    [
      {"country" : "Aruba", "population" : 103000},
      {"country" : "Afghanistan", "population" : 22720000},
      {"country" : "Angola", "population" : 12878000},
      {"country" : "Anguilla", "population" : 8000},
      {"country" : "Albania", "population" : 3401200},
      {"country" : "Andorra", "population" : 78000},
      {"country" : "Netherlands Antilles", "population" : 217000},
      {"country" : "Zimbabwe", "population" : 11669000}
    ];

    $scope.countries= [];
    $scope.sorted = [];
    $scope.loaded = false;

    $scope.load = function (){
      //show all CountriesController and population
      console.log("LOAD");
      $scope.loaded = true;
      for(var i = 0; i < Object.keys($scope.data).length; i++){
        $scope.countries.push($scope.data[i]);
        // console.log($scope.countries);
      }
    }

    $scope.sort = function (){
      // if($scope.loaded === true){
      console.log("SORT");
      $scope.sortByCountry = $scope.data.slice(0);  
      $scope.sortByCountry.sort(function(a,b){
        //isolate countries and population sort by name            
        var x = a.country;
        var y = b.country;

        return x < y ? -1 : x > y ? 1 : 0;
      });

      for(var i = 0; i < $scope.sortByCountry.length; i++){
        // console.log($scope.sortByCountry[i]);  
        $scope.countries.push($scope.sortByCountry[i]);
        console.log($scope.sortByCountry[i]);

      } 
      // }
    }
  }

Answer №1

Instead of appending to an existing array, consider sorting it and leaving it as is. I've streamlined your code to achieve the desired outcome. Additionally, you can utilize the orderBy helper from AngularJS to reduce the amount of code.

angular
  .module("frontendTest",[])
  .controller("CountriesController", CountriesController);

  CountriesController.inject =['$scope'];

function CountriesController($scope){

   $scope.data = 
   [
  {"country" : "Aruba", "population" : 103000},
  {"country" : "Afghanistan", "population" : 22720000},
  {"country" : "Angola", "population" : 12878000},
  {"country" : "Anguilla", "population" : 8000},
  {"country" : "Albania", "population" : 3401200},
  {"country" : "Andorra", "population" : 78000},
  {"country" : "Netherlands Antilles", "population" : 217000},
  {"country" : "Zimbabwe", "population" : 11669000}
  ];

  $scope.countries= [];
  $scope.sorted = [];
  $scope.loaded = false;

  $scope.load = function (){
    $scope.loaded = true;
    // Cloning data
    $scope.countries = JSON.parse(JSON.stringify($scope.data));
  }

  $scope.sort = function (){
    if($scope.loaded === true){ 
      $scope.countries.sort(function(a,b){
        var x = a.country;
        var y = b.country;

        return x < y ? -1 : x > y ? 1 : 0;
      });
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="frontendTest" ng-controller="CountriesController as countries">

        <header>
          <h1>Frontend Test</h1>  
          <div></div>
        </header>

        <section class="buttons">
          <input type="button" value="Load Countries" ng-click="load()">
          <input type="button" value="Sort Countries" ng-click="sort()">
        </section>


        <table class="table">
          <thead>
            <tr>
              <th class="col-md-6">Name</th>
              <th class="col-md-6">Population</th>
            </tr> 
          </thead>
         <tbody>
           <tr ng-repeat="country in countries track by $index" >

             <td class="col-sm-6">{{country.country}}</td>
             <td  class="col-sm-6">{{country.population}}</td>
           </tr>
         </tbody>
        </table>


        </body>

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 "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

What are the steps to integrate the vue-tweet-embed node package into vuejs2?

I am having trouble figuring out how to implement the vue-tweet-embed plugin in my Vue file. I keep getting an error message that says: Unknown custom element: - have you properly registered the component? If dealing with recursive components, ensure ...

What is the best way to determine if a Google Apps user is not an administrator?

We have developed an app for Google Apps and incorporated the "Integrate with Google" button [https://developers.google.com/apps-marketplace/button]. One issue we're facing is that when a user clicks on this button, they must be an administrator. Howe ...

Issues with implementing KoGrid within the Durandal JS framework

How do I properly bind a koGrid in my Durandal JS view page? The code provided below is not functioning as expected. View (HTML) <div id="functiontable" class="form-actions"> <div style="height: 200px" data-bind="koGrid: ...

Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari. ne ...

Ways to adjust brightness of a color using jquery

I have implemented color swatches and a slider to adjust the lightness and darkness of colors. I am seeking a way to change the lightness of the color based on the slider value. Here is what I have attempted: $("#darklight").slider({ range: "min", ...

Using the onClick event to dynamically alter the class name within a mapped array by leveraging Hooks

I'm currently working on developing an answer sheet, commonly known as a "Bubble sheet", where the user has the ability to select either "A,B,C, or D" and see the bubble transition from light mode to dark mode just like when marking with a physical pe ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

Encountering a 404 error while using Angular HTML5Mode setting

I recently enabled pretty URLs in my Angular application by switching to html5mode. However, whenever I try to refresh the page, I encounter a 404 error. For instance, if I access my app through , everything functions as expected. But when I attempt to r ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

Surprising Behavior of React's OnClick Event

Custom Component function ProductCard ({image, name, stats, id}){ let dispatch = useDispatch() let quantity = 1 return ( <> <div className="product-card" ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Instructions for inserting <tr></tr> after every fourth iteration of <td></td> in the loop

I am trying to create a list of twenty people with each tr containing 4 people, and I want to break from the loop after every fourth number. Each td value should be incremented in order. This is the code snippet I have been working on: <?php for ($i ...

Activate the template upon button press

Presented here is a list of items in the following format: <ul data-ng-controller="TodoController"> <li data-ng-repeat="todo in model.todos"> {{todo.id}} : {{todo.name}} <a href="#">Edit</a> <a href="#">Show< ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...