2014-08-27 54 views
8

我使用的UI路由器的新deferIntercept()無需重新加載 我的控制器更新瀏覽器網址:UI路由器deferIntercept和國家PARAMS

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) { 
    e.preventDefault(); 
    if ($state.current.name !== 'search') { 
    $urlRouter.sync(); 
    } 
    $urlRouter.listen(); 
}); 

有了這個代碼,在瀏覽器上的後退按鈕點擊將URL更改爲上一個,但我無法更新我的控制器狀態以反映此更改。 $ stateParams仍然包含用戶第一次加載頁面時設置的值。

當用戶點擊後退按鈕或手動更改URL時,更新控制器中$ state和$ stateParams對象的最佳方式是什麼?

謝謝!

回答

7

您致電$urlRouter.listen()應該放在事件處理程序之外。代碼段提供您應改爲:

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) { 
    e.preventDefault(); 
    if ($state.current.name !== 'search') { 
    $urlRouter.sync(); 
    } 
}); 

// Moved out of listener function 
$urlRouter.listen(); 

來源:official documentation for $urlRouter提供用於deferIntercept方法的代碼示例。它調用的地方$urlRouter.listen()監聽功能外:

var app = angular.module('app', ['ui.router.router']); 

app.config(function ($urlRouterProvider) { 

    // Prevent $urlRouter from automatically intercepting URL changes; 
    // this allows you to configure custom behavior in between 
    // location changes and route synchronization: 
    $urlRouterProvider.deferIntercept(); 

}).run(function ($rootScope, $urlRouter, UserService) { 

    $rootScope.$on('$locationChangeSuccess', function(e) { 
    // UserService is an example service for managing user state 
    if (UserService.isLoggedIn()) return; 

    // Prevent $urlRouter's default handler from firing 
    e.preventDefault(); 

    UserService.handleLogin().then(function() { 
     // Once the user has logged in, sync the current URL 
     // to the router: 
     $urlRouter.sync(); 
    }); 
    }); 

    // Configures $urlRouter's listener *after* your custom listener 
    $urlRouter.listen(); 
}); 
+0

的'$ state'參數撐不更新。但是 – Shamoon 2014-09-18 18:04:19

+0

我發現當我運行'如果(UserService.isLoggedIn())回報;'它不實際上,除非我專門調用同步,否則不會同步路由 – Maruf 2015-05-29 10:39:58