使用控制器和 routeParams 从 angularjs 中的 json 文件中检索特定信息

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

我有这个 json 文件

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

我有这两个控制器:

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

我试图 return 仅位于欧洲的国家/地区的信息,所以我写了这个控制器:

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

但是,我不完全确定如何 return 它并使用 routeProvider 进行显示,我并没有真正遵循文档给出的解释。谁能解释一下这将如何为我完成?

到 return 我做的整个列表:

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

你也可以这样写,简单明了javascript。

countryApp.controller('ContinentCtrl', function ($scope, countries) {
       var europeanCountries = [];
       for (var i = 0; i < countries.length; i++) {

           if (countries[i].continent === "Europe") {

               europeanCountries.push(countries[i]);

           }
       }
   });

你可以这样做,

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

并在您的路由文件中,

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