Tiago
Tiago

Reputation: 4480

Angular ui-router: accessing $stateParams on reload

In my Angular app, I have this route structure:

.state('mapping', {
    url: '/mapping',
    templateUrl: 'app/components/mapping/mapping.html',
    controller: 'MapCtrl as map',
    abstract: true,
    authenticate: true
})
.state('mapping.all', {
    url: '',
    templateUrl: 'app/components/mapping/partials/all.html',
    authenticate: true
})
.state('mapping.project', {
    url: '/:projectName',
    controller: 'ProjectCtrl as proj',
    templateUrl: 'app/components/mapping/partials/project.html',
    authenticate: true
})

The intended functionality is that when a user access 'mapping.project' the application will load all relevant information relative to that project using a projectID variable which is passed (invisibly) through $stateParams using ui-sref:

ui-sref="mapping.project({projectId: project.id, projectName: project.name})"

However this results in an unwanted behavior: when a user reloads the page when already on the 'mapping.project' state, nothing will be loaded because no $stateParams were effectively passed.

What would be the best way to get projectId on reload (and make sure my controller gets initiated again) without showing it on the URL?

Upvotes: 1

Views: 498

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

In this case, if we want our params to survive a page reload (or open in a new tab/window) they simply must be part of the URL. So the way to do this is to extend the URL definition with projectId:

.state('mapping.project', {
    url: '/:projectName?projectId',
    ...
})

that will add that projectId as "query string param". Another option is params nesting

.state('mapping.project', {
    url: '/:projectName/:projectId',
    ...
})

Check also this: How to pass parameters using ui-sref in ui-router to controller

Upvotes: 1

Related Questions