[英]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.