Angular RouteParams发送ID

时间:2015-05-20 15:19:55

标签: javascript angularjs routes ngroute

我正在尝试通过工厂使用$ 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;
           });
});

1 个答案:

答案 0 :(得分:0)

如何在您的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;
            });
        };  

}]);