2012-08-02 33 views
17

普通JavaScript有window.onbeforeunload。如何在HTML5路由中模擬AngularJS中的相同內容?AngularJS中window.onbeforeunload的路由等效性

有$ beforeRouteChange,但它不允許您取消事件,據我所知。

澄清:window.onbeforeunload將用於導航離開頁面,但不適用於頁面內導航,例如,只需通過HTML5歷史API從一個控制器轉到另一個控制器。

回答

15

有一個$locationChangeStart事件可以取消。

由於尚未記錄,因此以下是描述它如何影響$route服務的單元測試。 https://github.com/angular/angular.js/blob/v1.0.1/test/ng/routeSpec.js#L63

這不會像window.onbeforeunload那樣爲用戶提供確認。您需要攜帶自己的對話服務並重新啓動位置更改過程以獲得相同的效果(或者您可以使用同步$window.confirm)。

+1

是否爲'回button'工作? – Freewind 2013-03-09 06:32:54

+0

@Freewind有一個2013年5月1日簽到,使其工作後退按鈕:https://github.com/angular/angular.js/commit/dc9a580617a838b63cbf5feae362b6f9cf5ed986 – Nils 2013-05-10 02:39:57

22

補充一點:

$scope.$on('$destroy', function() { 
    window.onbeforeunload = undefined; 
}); 
$scope.$on('$locationChangeStart', function(event, next, current) { 
    if(!confirm("Are you sure you want to leave this page?")) { 
     event.preventDefault(); 
    } 
}); 
+5

對於角度路由器'$ stateChangeStart'應該使用。它不處理頁面刷新,因爲它是在'window.onbeforeunload'的情況下處理的。 – 2015-04-14 06:40:11

+0

我必須在'$ rootScope'而不是'$ scope'上監聽'$ stateChangeStart',這樣才能爲我工作。請注意,如果你這樣做,當你的當前範圍被銷燬時('$ scope。$ on('$ destroy,...)'),你將需要手動取消註冊這個事件監聽器。 – 2017-02-16 20:20:53

5

如果您正在使用角UI的路由器,你需要使用$stateChangeStart而不是$locationChangeStart

+1

完全正確!當控制器「啓動」時調用'$ locationChangeStart'和angular-ui-router,而不是在用戶離開頁面時調用。 – 2016-01-20 10:41:08

0

使用UI-Router版本1.0.0+時,請使用$transitions.onStart而不是$stateChangeStart。請參閱transition hooks文檔。

$stateChange*事件被棄用的版本1.0.0(source):

所有狀態的事件,(即$stateChange*和朋友)都現在已經過時 並默認爲禁用。而不是監聽事件,請使用 Transition Hook API。

示例代碼中止的轉換(source):

$transitions.onStart({}, function(transition) { 
    if (transition.to().name === 'unreachable') { 
    return false; 
    } 
}