這可以通過多種方式來實現,
1-使用$ locationChangeStart技術,驗證這是否顯示消息之前的當前位置。下面的例子,
$scope.$on('$locationChangeStart', function(event, next, current) {
// match Current URL and If it true show message.
if (current.match("\/yourCurrentRoute")) {
var answer = confirm("Are you sure you want to leave this page?");
if (!answer) {
event.preventDefault();
}else {
//Do whatever else you want to do
}
}
});
2 - 如果你正在使用的用戶界面,路由器具有的OnExit回撥選項,下面 例如,
$stateProvider.state("contacts", {
template: "<h1>{{title}}</h1>",
resolve: { title: 'My Contacts' },
controller: function($scope, title){
$scope.title = title;
},
onExit: function(title){
if(title){ ... do something ... }
}
})
3 - 有一種無角的方式做到這一點以及。
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
4 - 使用此指令,如果這個頁面有形式,它會自動在窗體卸載清理自己的身體。如果您想阻止提示(例如,因爲您成功保存了表單),請調用$ scope.FORMNAME。$ setPristine(),其中FORMNAME是要阻止提示的表單的名稱。
.directive('dirtyTracking', [function() {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function() {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
5-還有另外一種方法可以使用$ destroy,當控制器被銷燬時它會被觸發,把它寫在控制器裏面。
$scope.$on('$destroy', function() {
// display error message
});
你應該檢查http://plnkr.co/edit/YWr6o2?p=preview –
,但我需要完全opposite-如果我離開一個頁面比我需要在進入時間的事件,而不是。 – quma