如何使用角度检测浏览器后退按钮单击事件? [英] How to detect browser back button click event using angular?
问题描述
是否可以检测到用户通过浏览器中的历史后退按钮进入了页面?最好我想使用 angular.js 检测这个动作.
Is it possible to detect that a user entered a page through using the history back button in his browser? Preferably I want to detect this action using angular.js.
我不想使用角度路由.如果用户提交表单并成功提交到服务器并重定向后,它也应该可以工作,如果用户使用浏览器的后退按钮返回表单也应该是可能的.
I do not want to use angular routing. It should also work if a user submits a form and after a successful submit to the server and a re-direct, it should also be possible if the user goes back to the form using the back button of the browser.
推荐答案
这是 Angular 的解决方案.
Here is a solution with Angular.
myApp.run(function($rootScope, $route, $location){
//Bind the `$locationChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});
$rootScope.$watch(function () {return $location.path()}, function (newLocation, oldLocation) {
if($rootScope.actualLocation === newLocation) {
alert('Why did you use history back?');
}
});
});
我正在使用运行块来启动它.首先我将实际位置存储在 $rootScope.actualLocation 中,然后我听 $locationChangeSuccess 并且当它发生时我用新值更新 actualLocation.
I am using a run block to kickstart this. First I store the actual location in $rootScope.actualLocation, then I listen to $locationChangeSuccess and when it happens I update actualLocation with the new value.
在 $rootScope 中,我观察位置路径的变化,如果新位置等于 previousLocation 是因为 $locationChangeSuccess 没有被触发,这意味着用户已经使用了历史记录.
In the $rootScope I watch for changes in the location path and if the new location is equal to previousLocation is because the $locationChangeSuccess was not fired, meaning the user has used the history back.
这篇关于如何使用角度检测浏览器后退按钮单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!