我使用 ui-router 的新 deferIntercept() 来更新浏览器 url 而无需重新加载
我的控制器:
$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
e.preventDefault();
if ($state.current.name !== 'search') {
$urlRouter.sync();
}
$urlRouter.listen();
});
使用此代码,单击浏览器的后退按钮会将 URL 更改为前一个,但我无法更新控制器状态以反映此更改。
$stateParams 仍然包含用户首次加载页面时设置的值。
当用户单击后退按钮或手动更改 URL 时,更新控制器内的 $state 和 $stateParams 对象的最佳方法是什么?
thanks !
您致电$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();
Source: The 官方文档$urlRouter http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.%24urlRouterProvider提供了一个代码示例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();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)