Refreshing page removes non-URL $stateParam (ui-router)

Issue

Im using UI-Router in my application and I have a state parameter where it doesn’t really make sense for it to be part of the url. According to the documentation I am creating the parameter without specifying it in the state url, as such:

.state('contact', {
        url: "/:contactId/contact",
        params: {
            otherParam: null
        },
        templateUrl: 'contacts.html'
    })

This works as intended, but I noticed that if I manually refresh the page, the parameter gets reset to the default null.

For example, if I redirect to the state as such:

$state.go('contact', {contactId: 42, otherParam: 11});

Everything works as expected ($stateParams.contactId is 42, $stateParams.otherParam is 11)
However, once I refresh the page, $stateParams.contactId is still 42, but $stateParams.otherParam has been set back to null. Is it possible to persist this non-URL parameter across a browser refresh?

Solution

It’s sort of possible, but you shouldn’t do it. If it is something that should persist on refresh, that means that by definition it SHOULD be in the URL, since you expect it to be a component of the resource.

If you really really want to break convention and do this, you’ll need to do something that saves the data in window.name and retrieves it on reload. This is definitely an anti-pattern, and anyone could get access to that data, but like I said, it’s possible.

Answered By – Dan Crews

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.