Angular UI router - access state params in parent

Darwin Tech picture Darwin Tech · Apr 8, 2014 · Viewed 12.8k times · Source

I have an Angular App using the great ui-router.

My setup looks like:

.config( function ($stateProvider, $urlRouterProvider) {

    $stateProvider

    // PROJECT DETAIL
    .state('project', {
        url: '/project/:projectId/',
        resolve: {
            /* some base api calls */
        },
        views: {
            'task-list': {
                templateUrl: 'partials/task_list.tmpl.html',
                controller: 'TaskListCtrl',
                resolve: {
                    tasks: function ($stateParams, ConcernService) {
                        return ConcernService.get('project-tasks/', $stateParams.projectId);
                    },
                }
            },
            'concern-instance': {
                /* some resolved variables */
            }
        }
    })
    .state('project.task', {
        url: 'task/:taskId/',
        views: {
            'concern-instance@': {
                /* some different resolved variables */
            },
        }
    })

This all works like butter. However in my task_list template when in state project.task, I want to be able to access the taskId param so I can highlight active nav links, even when the url is #/project/123/task/456/ the taskId is empty. I understand that this is because templates only have access to params declared for that state. So if I want to get the taskId in the project.task state, how should I do it? Do I need to re-declare the task-list in project.task?

Answer

goodies4uall picture goodies4uall · Jun 23, 2015

In the UI-Router documentation here they explain that

"the $stateParams object will only contain the params that were registered with that state."

You can only have access to parent state parameters in a child state using the resolve property on the parent.

Put this on your 'project' state (parent):

...    
resolve: {
    // Expose projectId parameter to child states
    projectId: ['$stateParams', function ($stateParams) {
        return $stateParams.projectId;
    }]
},

Then inside your controller for your state 'project.task' (child) you should have access to both

$stateParams.projectId

and

$stateParams.taskId