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]);
}
// }
}
}