amack459 amack459 - 3 months ago 15
Javascript Question

How to sort data with ng-click after already loaded with ng-click angular

I'm trying to get the information in the table to change using ng-click. I have the functions that load and sort and work correctly,
but I'm not able to switch between the two. By this I mean, if I click
load, I can't sort after and vice versa. I think it's because I reset
countries with each click, but I'm not sure how to recognize them both
if I have them in different variable using ng-repeat. Help Please!!

<!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

The problem was that you're appending to existing array when you can sort it and leave as is. I've simplified your code and it should work as you wanted to. You can also use orderBy helper from AngularJS which should reduce an 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>

Comments