Search code examples
htmlangularjscontrollerroute-provider

Retrieve specific information from json file in angularjs using controllers and routeParams


I have this json file

 [{
        "name": "China",
        "continent": "Asia",
        "id": 1
      },
      {
        "name": "UK",
        "continent": "Europe",
        "id": 2
      },
      {
        "name": "Germany",
        "continent": "Europe",
        "id": 3
      }]

And I've got these two controllers:

 countryApp.controller('CountryListCtrl', function($scope, countries) {
            countries.list(function(countries) {
                $scope.countries = countries;
            });
        });

        countryApp.controller('CountriesDetailCtrl', function($scope, $routeParams, countries) {
            countries.find($routeParams.countryId, function(country) {
                $scope.country = country;
            });
        });

I'm trying to return only the information of countries that are situated in Europe so I wrote this controller:

countryApp.controller('ContinentCtrl', function($scope, countries) {
            countries.list(function(countries) {
                if (country.continent = "Europe") {
                    $scope.country = country;
                }
            });
        });

However, I'm not entirely sure how to return it and display using the routeProvider and I don't really follow the explanation given by the documentation. Can someone explain how this would be done for me?

To return the entire list I do:

countryApp.config(function($routeProvider) {
            $routeProvider.
            when('/', {
                templateUrl: 'country-list.html',
                controller: 'CountryListCtrl'
            }).
            when('/Europe', {
                templateUrl: 'country-list.html',
                controller: 'ContinentCtrl'
            });
});

Solution

  • you can do like ,

    countryApp.controller('ContinentCtrl', function($scope, countries, $routeParams) {
            countries.list(function(countries) {
              for (var i=0; i < countries.length; i++) {
                   if (countries[i].continent == $routeParams.continent) {
                       $scope.countries.push (countries[i]);
                   }
                }
            });
        });
    

    and in your routing file,

    countryApp.config(function($routeProvider) {
            $routeProvider.
            when('/', {
                templateUrl: 'country-list.html',
                controller: 'CountryListCtrl'
            }).
            when('continents/:continent', {
                templateUrl: 'country-list.html',
                controller: 'ContinentCtrl'
            });
    });