我需要一種方法來在當前頁面上存在未保存的更改時中斷導航到新頁面的用戶。我實現了這裏的解決方案的修改版本:
http://weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs-controllers
不過,我在瀏覽器中看到的是,只要一個鏈接,用戶點擊,視圖的變化和新的控制器負荷完全同時顯示模態對話框。當用戶點擊「取消」並觸發event.preventDefault時,用戶只需結束新視圖。這很奇怪,因爲我讀過的所有內容都表明這是可接受的方法,而且似乎沒有人會遇到這個問題。然而,我不能在我的生活中看到我的代碼出了什麼問題。
下面是用於處理位置變化的主要應用功能(ModalService只是包裝的角度引導$模式服務):
onRouteChangeOff = $rootScope.$on('$locationChangeStart', routeChange);
function routeChange(event, newUrl, oldUrl) {
//Navigate to newUrl if the form isn't dirty
if (!$rootScope.unsavedChanges) return;
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Ignore Changes',
headerText: 'Unsaved Changes',
bodyText: 'You have unsaved changes. Leave the page?'
};
ModalService.showModal({}, modalOptions).result.then(function() {
$rootScope.unsavedChanges = false;
$location.path(newUrl); //Go to page they're interested in
}
, function() {
event.preventDefault();
});
return;
}
任何想法?
在打開模式之前防止默認 – vil 2014-09-19 04:35:05
這沒有幫助我害怕。新的控制器/視圖在模式打開之前已經加載,並且不管我是否調用event.preventDefault。 – 2014-09-19 07:18:17
只有在更改視圖之前,纔會在更改開始時調用此函數。只需嘗試在路由更改函數中只有event.preventDafault,以檢查它是否僅限制url中的更改。然後,您可以檢查功能中是否有其他錯誤。 – Kop4lyf 2014-09-19 08:07:25