ui-router deferIntercept 和 state 参数 [英] ui-router deferIntercept and state params
问题描述
我使用 ui-router 的新 deferIntercept() 来更新浏览器 url 而不重新加载我的控制器:
I use the new deferIntercept() of ui-router to update the browser url without reloading my controller:
$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
e.preventDefault();
if ($state.current.name !== 'search') {
$urlRouter.sync();
}
$urlRouter.listen();
});
使用此代码,单击浏览器的后退按钮会将 URL 更改为前一个,但我无法更新控制器状态以反映此更改.$stateParams 仍然包含用户第一次加载页面时设置的值.
With this code, a click on the browser's back button changes the URL to the previous one, but I'm not able to update my controller state to mirror this change. $stateParams still contains the values set when the user first loaded the page.
当用户单击后退按钮或手动更改 URL 时,更新控制器内的 $state 和 $stateParams 对象的最佳方法是什么?
What's the best way to update the $state and $stateParams objects inside my controller when the user click the back button or change the URL manually ?
谢谢!
推荐答案
您对 $urlRouter.listen()
的调用应该放在事件处理程序之外.您提供的代码片段应更改为:
Your call to $urlRouter.listen()
should be placed outside the event handler. The code snippet you provided should be changed to:
$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
e.preventDefault();
if ($state.current.name !== 'search') {
$urlRouter.sync();
}
});
// Moved out of listener function
$urlRouter.listen();
<小时>
来源:$urlRouter
的官方文档提供了 deferIntercept
方法的代码示例.它将对 $urlRouter.listen()
的调用置于侦听器函数之外:
Source: The official documentation for $urlRouter
provides a code sample for the deferIntercept
method. It places the call to $urlRouter.listen()
outside of the listener function:
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();
});
这篇关于ui-router deferIntercept 和 state 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!