我试图通过工厂使用$ routeParams将ID发送到控制器,但是它不起作用。
我的$ routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl'
});
我的工厂:
myApp.factory('eventRepo', ['$http', function($http) {
var urlBase = 'php/api.php';
var eventRepo = {};
eventRepo.getEvent = function (id) {
return $http.get(urlBase + '?eventID=' + id);
};
return eventRepo;
}]);
我的控制器:
myApp.controller('eventPageCtrl', ['$scope', '$routeParams', 'eventRepo',
function ($scope, $routeParams, eventRepo) {
$scope.getEvent = function (id) {
eventRepo.getEvent($routeParams.eventId)
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
当在控制器内部而不是在工厂内处理$ http.get()时,它工作正常,所以我认为我没有正确传递$ routeParams吗?也许这行引起问题
eventRepo.getEvent($routeParams.eventId)
?目前可以使用,但是尝试在控制器外部使用$ http.get():
myApp.controller('eventPageCtrl', function($scope, $http, $routeParams) {
$http.get("php/api.php?eventID="+$routeParams.eventId).success(function(data){
$scope.eventsDetail = data;
});
});
最佳答案
如何在routeProver中使用resolve
并返回eventId
然后将其注入controller
..示例:
$ routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl',
resolve : {
eventId: function($route, $location) {
var eventId = $route.current.params.eventId;
return eventId;
});
控制器:
myApp.controller('eventPageCtrl', ['$scope', 'eventId', 'eventRepo',
function ($scope, eventId, eventRepo) { //add it as a dependency
$scope.eventId = eventId; //you can check this to see if its being assigned
$scope.getEvent = function (eventId) { //Edit: eventId added here
eventRepo.getEvent(eventId) //Edit: eventId passed
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
关于javascript - Angular RouteParams发送ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30353879/