Display country data with AngularJS and $http

by dshilkret

HTML

<div ng-app="countryApp" ng-controller="CountryCtrl">
  <h3>Top 10 Countries (via $http)</h3>
  <div ng-if="error">{{ error }}</div>
  <div ng-if="!countries.length">Loading...</div>

  <div ng-repeat="country in countries">
    <strong>{{$index + 1}}. {{country.name.common}}</strong> – 
    Region: {{country.region}}, 
    Population: {{country.population | number}}
  </div>
</div>

JavaScript

angular.module('countryApp', [])
  .controller('CountryCtrl', function($scope, $http) {
    $scope.countries = [];
    $scope.error = null;

    $http.get('https://corsproxy.io/?https://restcountries.com/v3.1/all?fields=name,region,population')
      .success(function(data) {
        $scope.countries = data
          .sort(function(a, b) {
            return a.name.common.localeCompare(b.name.common);
          })
          .slice(0, 10);
      })
      .error(function(data, status) {
        console.error('API error:', status);
        $scope.error = 'Failed to load countries.';
      });
  });