2014-08-27 104 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