[英]Angularjs History back button not working
我一直在查看Angularjs后退按钮事件的大量示例,但是没有一个示例对我有用。 每当按下浏览器的后退按钮时,我的代码都不会收到该事件。 我已经挠头好几天了。
我要做的只是收到警报,询问用户是否确定要返回并丢失所有数据。
下面是我一直在尝试的代码。 它是其他示例的副本,但带有完整的代码。
我尝试使用$ scope而不是$ rootscope在控制器中添加$ on,我尝试在routechangestart上进行监视,似乎没有任何东西可以抓住后退按钮。
有人有一个完整的小例子或告诉我我做错了什么吗?
var BackButtonTest = angular.module('BackButtonTest', ['ngRoute']);
BackButtonTest.controller('backbuttonCtrl', function($scope, $location, $route) {
});
BackButtonTest.run(function($rootScope, $route, $location){
//Bind the $locationChangeSuccess event on the //rootScope, so that we don't need to
//bind in induvidual controllers.
$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});
$rootScope.$watch(function () {
return $location.path()
}, function (newLocation) {
if($rootScope.actualLocation === newLocation) {
// run a function or perform a reload
}
});
});
我使用的HTML代码如下:
<!doctype html>
<html lang="en" ng-app="BackButtonTest">
<head>
<meta charset="utf-8">
<title>BackButtonTest App</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script src="app.js"></script>
<body ng-controller="backbuttonCtrl as bbc">
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-push-2">
Some random text
</div>
</div>
</div>
</body>
</html>
我建议使用$locationChangeStart
因为您可以在这里“防止”更改的发生。
逻辑基本上是:
preventDefault
(这将阻止更改发生) 该链接详细介绍了操作方法: http : //weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.