如何使用angular检测浏览器后退按钮单击事件? [英] 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.
这篇关于如何使用angular检测浏览器后退按钮单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!