事件发生后重定向到主页.preventDefault.

Redirect to home page after event.preventDefault..?

本文关键字:主页 preventDefault 重定向 事件      更新时间:2023-09-26

我在控制器内的angularjs脚本文件中有这个。

var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
                event.preventDefault();
                $location.url("/");
});

它的部分工作方式实际上并不是我想要的工作方式。此代码通过询问是否停留在页面上来阻止页面重新加载。如果用户仍然想通过单击离开页面来重新加载页面,我想重定向到我的angular应用程序的主页。我试了好几种代码,但似乎都不起作用。有人帮我回答吗?提前谢谢。

假设您在控制器中,并且您有一个$scope变量

$scope.$on('$locationChangeStart', function( event ) {
    event.preventDefault();
    if (confirm("Are you sure you want to leave this page?")) {
        $location.url("/");
    }
});

这应该有效,让我知道(首先,如果我理解你的问题)