在同一个控制器中处理不同的routeParams

时间:2018-05-10 13:41:26

标签: javascript angularjs

我有一个控制器,每个不同的路径传递不同的参数。我的routes.js文件看起来像这样 -

.when('/event/:eid/edit-question/:qid', {
            templateUrl: 'views/edit-question.html',
            controller: 'eventController',
            controllerAs: 'eventCtrl',
            resolve: {
                "check": function (authService, $location) {
                    if (!authService.isLoggedIn()) {
                        $location.path('/login');
                    }
                },
                "params": function ($route) {
                    return $route.current.params;
                }
            }
        })
        .when('/event/edit-event/:eid', {
            templateUrl: 'views/edit-event.html',
            controller: 'eventController',
            controllerAs: 'eventCtrl',
            resolve: {
                "check": function (authService, $location) {
                    if (!authService.isLoggedIn()) {
                        $location.path('/login');
                    }
                },
                "params": function ($route) {
                    return $route.current.params;
                }
            }
        })

我在加载控制器之前解析了路径参数。 我的控制器功能看起来像这样 -

myApp.controller('eventController', ['$location','$rootScope', 'params', 'authService', 'apiService', function ($location,$rootScope, params,authService, apiService) {
 let dash = this;
//all the route parameters will be resolved and stored here
 dash.params = params;
 //get the details of an event
    dash.getTheEventDetail = () => {
        apiService.getEventDetail(dash.params.eid).then(function successCallBack(response){
           console.log(dash.params.eid);
            dash.eventDetail = response.data.data;
        });
    }
    dash.getTheEventDetail();

    //get the detail of a question for the qid passed as parameter

    dash.viewQuestion = () => {
        console.log(dash.params.qid);
        console.log(dash.eventDetail); 
        dash.questionDetail = dash.eventDetail.questions.filter(question => question._id === dash.params.qid);
        console.log(dash.questionDetail);
    }

当我尝试访问路由/事件/:eid / edit-question /:qid时,viewQuestion函数在getTheEventDetail之前执行,因为dash.eventDetail仍未定义 viewQuestion在编辑问题视图中的控制器初始化时被调用,如下所示。

<div ng-init="eventCtrl.viewQuestion()"></div>

可以在getTheEventDetail()的末尾调用viewQuestion函数。但是这会导致每次调用getTheEventDetail时调用viewQuestion。在这种情况下,有一种很好的方法来处理routeParams。

0 个答案:

没有答案