防止页面重新加载状态

时间:2018-01-02 09:27:39

标签: angularjs angular-ui-router

如果使用AngularJs 1.6和启用了Html5模式的UI-Router从窗口重载/ F5键打开应用程序,如何防止加载某些状态。

我的UI-Router配置的一部分:

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

如果在浏览器中粘贴链接或F5打开页面,我需要阻止加载“模态”状态。

“modalform”状态在模态窗口中打开,我不想在页面重新加载时打开。刷新事件结束后,应该可以手动访问状态。

如果url中存在某些字符串,我试图检查“root”状态但是root似乎不知道除了他自己以外的其他状态。

我还可以检查“模态”控制器,如果状态是从F5打开但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以侦听状态更改事件(或在较新版本的UI路由器中实现转换挂钩),并检查以前状态是否存在。

我们的想法是,如果通过页面刷新或URL粘贴访问某个州,则之前的状态将不存在。

$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");
  }
})

并且,如果从任何其他州导航,modalform状态将是可访问的,因为那时toState将存在。

相关问题