0

How do I prevent certain states from being loaded if application is opened from window reload/F5 key using AngularJs 1.6 and UI-Router with Html5 mode enabled.

Part of my UI-Router configuration:

.state("recordform", {
            url: "/form/:formid/:recordid",
            templateUrl: "Form.html",
        })
        .state("modalform", {
            parent: "RecordForm",
            url: "/modalform/:modalformid/:modalrecordid",
            templateUrl: "ModalForm.html"
        })

I need to prevent loading "modalform" state if page is opened by pasting link or F5 in browser.

The "modalform" state is opened in modal window which I don't want to open on page reload. The state should be accessible manually after refresh event is over.

I tried to check in "root" state if there is certain string in url but root seems to don't know about other states but himself.

I could also check in "modalform" controller if the state is opened from F5 but I don't know how to do that.

Piotshe
  • 59
  • 7
  • Check this answer it will help: https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript – pegla Jan 02 '18 at 09:42
  • I think the "performance.navigation.type" property will make it unable to reach the "modalform" state manually after refresh. I want discard the state only in the reload event. After that the state should be accessible. – Piotshe Jan 02 '18 at 09:51

1 Answers1

1

You can listen to the state change event (or implement a transition hook in newer version of UI router), and check for the existence of previous state.

The idea is that if a state is visited by a page refresh or URL paste, then the previous state will not exist.

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) {
  if (!fromState && toState.name === 'modalform') {
    event.preventDefault(); // Prevent access to the state

    // optionally redirect to other state if required
    $state.go("your_default_state");
  }
})

And, the modalform state will be accessible if it is navigated from any other state, because at that time, toState will exist.

31piy
  • 23,323
  • 6
  • 47
  • 67