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

Discovering the smallest and largest values in an object literal using JavaScript

I am looking to extract the minimum value from an object literal and utilize it in AngularJS, as shown below: scope.data = { 'studentName' : "Anand", 'socialStudies' : "98", 'english' : "90", 'math' ...

Automated Submission and Online Posting of (Web Form) with JavaScript Script

Is there a way to automatically fill out the form on my webpage ( ) using a JavaScript function with specific parameters? The source code for the webpage can be found here: webpage sourcecode script enter image description here ...

Setting up Nest JS by installing necessary packages

I created a package for my project and successfully installed it in my repository. However, I am facing an issue where I cannot import the functions from that package. "compilerOptions": { "module": "commonjs", " ...

Sending an object over to a different page

Need some assistance with displaying JSON data that is being repeated using ng-repeat. { "title": "image title", "description": "Lorem ipsum dolor sit amet, per ea ferri platonem voluptaria, ea eum ubique ornatus interpretaris. Dolore erroribus reprimique ...

Creating a list of identical elements with shared attribute values using nightwatch.js or JavaScript - a step-by-step guide

I have been using nightwatch.js for automating tests on a web application, and I am facing difficulties in creating a list of elements that share common values in their attributes. Below is an example: The first three spans with a common value for the att ...

"Master the art of drag and drop in Dojo: Implementing a handler for the drop

My list is structured as follows: <div dojoType="dojo.dnd.Source" id="myList"> <div class="dojoDndItem">item 1</div> <div class="dojoDndItem">item 2</div> <div class="dojoDndItem">item 3</div> </div ...

What is the best way to shorten text in React/CSS or Material UI based on the line height multiples?

I'm facing an issue with creating a Material UI card that contains text. My goal is to set a fixed height for the card and truncate the text if it exceeds 3 lines. Can anyone suggest the best approach to achieve this? Here's the code snippet I&a ...

Adjust the overflow to automatically decrease at regular intervals

Is there a way to make the scroll automatically move down a bit every few seconds, revealing more text in the process? Here's an example of how I want it to work: http://jsfiddle.net/Bnfkv/2/ ...

Issue with Chrome related to svg getScreenCTM function

Check out the jsFiddle demo I am attempting to utilize the getScreenCTM function to retrieve the mouse position based on SVG image coordinates. It seems to work in IE and Firefox, but not in Chrome. When I define the attributes width and height in the SV ...

Guide to aligning the center of a div with the mouse cursor using JavaScript during mouse movement

I've been trying to center a div element with the mouse cursor, following its movement. However, the current code I have offsets the positioned div from the cursor instead of aligning it perfectly. PROCESS The concept behind my code is to display an ...

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

What is the best method for incorporating a YouTube embedded video into an image carousel using HTML and CSS?

I'm encountering an issue with my product carousel that includes an image and a video. The image displays correctly, but when I attempt to click on the video to have it appear in the main carousel view, it doesn't function as expected. Here is a ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Delete the child element if it is present in an HTML document

removeConnection(event) { let parentElement = document.getElementById('RemoveElement'); let childElement = document.getElementById(event.target.id); parentElement.removeChild(childElement); } Whenever I try to remove the child ...

I'm struggling to grasp how to effectively utilize a JSON Object in this situation

In my coding project, I am looking to utilize Javascript in order to create a JSON or array that will house pairs of data for 'id' and 'ip'. This way, if I need to retrieve the 'ip' for a specific 'id=123', I can eas ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Encountering a 404 Error on all routes except the home page when working with the Express Application Generator

While working on developing a day planner, I encountered an issue with the routes. I am consistently receiving a 404 error for any route other than the main Home page route (index or "/"). Below is the content of the app.js file: var express = require(&ap ...

Collaborative gaming experience with three.js and socket.io

I created a basic scene in three.js that I find really fun to interact with. However, I wanted to enhance it by adding multiplayer functionality through a socket.io server. To achieve this, I prompt the user for their username: var username = prompt("what ...

Unlock the Power of jQuery Plugins: Implementing Global Settings Modifications

I have developed a jQuery plugin ( https://github.com/OscarGodson/jKey ) and some users are requesting localization support. My initial idea was to add an additional parameter in the plugin for localization, such as: $(window).jkey('?',callback, ...

Require the field if the country selected is the United States

I am working on implementing form validation for the STATES dropdown, but I want it to only be required if the selected country is USA or CANADA. Currently, my validation works regardless of the country selection. It forces the user to select a state even ...