2013-09-25 28 views
34

我正在開發一個AngularJS應用程序,該應用程序具有捕獲所有路線(例如,.when('/:slug', {...)),這是支持應用程序以前(非角度)版本的傳統網址格式所必需的。響應catch的控制器都會嘗試提取一個相關的對象,如果沒有找到,則使用$location.path方法重定向到404頁面。這可以讓用戶訪問404頁面,但是當用戶在瀏覽器中回訪時,他們會將他們帶回頁面,首先迫使他們進入404頁面,並最終無法擺脫循環。AngularJS重定向無需推送歷史狀態

我的問題是,如果有1)用於處理這種情況下一個更好的模式,或者2)如果有一種方法來重新路由不強制在瀏覽器歷史按壓狀態的用戶?

回答

56

您可以更改URL,而不添加到歷史狀態,發現here在「替換法」。這與調用HTML5的history.replaceState()實際上是一樣的。

$location.path('/someNewPath').replace(); 

我還沒有發現可以更改視圖而不更改網址。我發現改變視圖的唯一方法是更改​​位置路徑。

+0

你利用替換法說,你可以與網頁上沒有改變其他狀態更新網址是什麼?我的意思是改變URL的純粹美容效果?因爲這是什麼讓頁面覆蓋(與正確的網址)類似pinterest的可能性。 – CMCDragonkai

+0

我寫了前一段時間,但我認爲該URL變化仍然觸發角事件重新路由,但是這會阻止它顯示在瀏覽器歷史記錄,這樣至少你的背部按鈕仍然有效了。 – thrashr888

+3

不錯。它也適用於'.search()' – vtortola

3

路由系統的正常運行是爲$route服務注意$locationChangeSuccess事件,然後開始加載路由。完成加載模板後,執行解析步驟並實例化控制器,然後再廣播$routeChangeSuccess事件。 $routeChangeSuccessng-view指令的監控,這就是它知道一旦新路線準備就換掉模板和範圍。

與所有上述表示的,它可能工作有應用程序代碼模擬$route服務的行爲通過更新當前路線和發射路徑改變事件獲得視圖更新:

var errorRoute = $route.routes[null]; // assuming the "otherwise" route is the 404 
// a route instance is an object that inherits from the route and adds 
// new properties representing the routeParams and locals. 
var errorRouteInstance = angular.inherit(
    errorRoute, 
    { 
     params: {}, 
     pathParams: {}, 
    } 
); 
// The $route service depends on this being set so it can recover the route 
// for a given route instance. 
errorRouteInstance.$$route = errorRoute; 

var last = $route.current; 
$route.current = errorRouteInstance; 

// the ng-view code doesn't actually care about the parameters here, 
// since it goes straight to $route.current, but we should include 
// them anyway since other code might be listening for this event 
// and depending on these params to behave as documented. 
$rootScope.broadcast('$routeChangeSuccess', errorRoute, last); 

以上假設您的「其他」路線沒有任何「解決」步驟。它還假設它不會期望任何$routeParams,這對於「否則」路線當然是正確的,但如果您使用不同的路線,則可能不是真實的。

目前還不清楚上面什麼取決於實施細節與接口。該$routeChangeSuccess事件肯定是記錄,但路線實例的$$route財產似乎是考慮到其雙美元符號名的路線系統的實現細節。 「否則」路線在關鍵路徑null中保存的路線表中的細節可能也是一個實施細節。所有這一切都表明,這種行爲在未來的AngularJS版本中可能不會保持功能。

欲瞭解更多信息,你可以參考the ng-view code that handles this event,這是最終以上代碼試圖取悅,以及the event emitting code,我作爲上述示例的基礎。從這些鏈接中可以推斷出,本文中的信息源自AngularJS的最新主分支,在撰寫本文時,分支標記爲1.2.0-快照。