我正在开发 AngularJS 网络应用程序。 我有以下路由配置:
$routeProvider.
when("/drivers", {templateUrl: "partials/drivers.html", controller: "driversController"}).
when("/drivers/:id",{templateUrl: "partials/driver.html", controller: "driverController"}).
otherwise({redirectTo: '/drivers'});
}]);
因此,为了传递 JSON 的 ID,我在 service.js 文件中使用了以下方法
F1API.getDriverDetails = function(id) {
return $http({
method: 'JSONP',
url: 'http://localhost:8000/app/data/' + id + '/driverStandings.json?callback=JSON_CALLBACK'
});
}
F1API.getDriverRaces = function(id) {
return $http({
method: 'JSONP',
url: 'http://localhost:8000/app/data/' + id + '/results.json?callback=JSON_CALLBACK'
});
}
return F1API;
});
但现在我遇到了困难。我需要这种方法来在一个对象中分配一个司机和他的比赛。但是我需要这个 ID,所以我在我的 controller.js
中尝试了/* Driver controller */
controller('driverController', function($scope, $routeParams, F1APIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
F1APIservice.getDriverDetails(id).success(function(response){
$scope.driver = response.MRData.StandingsTable[0].DriverStandings[0];
});
F1APIservice.getDriverRaces(id).success(function(response){
$scope.races = response.MRData.RaceTable.Races;
});
});
在我构建我的网络应用程序时,Id 是未知的。我做错了什么?
最佳答案
在您的 Controller 中,您将 $routeParams.id
分配给 $scope.id
,然后调用 getDriverDetails
和 getDriverRaces
只有 id
,这是未定义的。您需要这样调用它们:getDriverDetails( $scope.id )
。
关于javascript - AngularJS:如何通过 Controller 中的服务方法传递 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159676/