【发布时间】:2016-09-16 16:20:43
【问题描述】:
我一直在查看 Angularjs Back Button 事件的大量示例,但没有一个示例对我有用。每当按下浏览器后退按钮时,我的代码都不会收到事件。这几天我一直在摸不着头脑。
我想要做的只是收到一个警报,询问用户是否确定他们想要返回并丢失所有数据。
以下是我一直在尝试的代码。它是其他示例的副本,但具有完整的代码。
我尝试使用 $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>
【问题讨论】:
-
这篇文章会有所帮助:weblogs.asp.net/dwahlin/…
标签: javascript jquery angularjs