在不重新加载页面的情况下更改 angular-ui-router 的 url [英] Change url of angular-ui-router without reloading page

查看:29
本文介绍了在不重新加载页面的情况下更改 angular-ui-router 的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望更改 URL 以驱动我的应用程序,并希望更改应用程序以 更改 URL,但实际上不更改状态.

I'd like for changes in the URL to drive my application, and for changes in the application to change the URL, but not actually change state.

我有这样的路线.国家/城市的例子有点做作,希望不会混淆.实际应用程序中的关系有点分层.不过,子视图似乎不合适,因为不需要嵌套视图.

I have a route like this. The country/city example is a bit contrived, hopefully that doesn't confuse things. The relationship in the real application is somewhat hierarchical. Child views don't seem a fit though because there's no need for nested views.

$stateProvider.state( 'viewMap', {
  url: '/viewMap/:country/:city',
  templateUrl: 'pages/viewMap/viewMap.html',
  controller: 'ViewMapController'
};

在 ViewMapController 中,我可以根据 $stateParams.country.city 构建页面.随着这些值的变化,我的应用程序会做出反应,我希望 url 保持同步.但是,我不想重新加载整个页面.我只想更新 url 并将历史状态推送到堆栈.

In ViewMapController, I can construct the page based on $stateParams.country and .city. As these values change, my application reacts and I want the url to stay in sync. I don't want to reload the whole page, however. I just want to update the url and push a history state on to the stack.

我知道我可以手动构造一个字符串:

I understand I could manually construct a string:

updateUrl = function() {
 window.location.hash = '#/viewMap/'+ $stateParams.country +'/'+ $stateParams.city
}

这感觉很脆弱,因为我构建字符串的方式与框架解析它的方式是分开的.我希望框架根据当前参数为我构建一个字符串,但是 $state.href('.') 描述了当前路由,它不包括 $stateParams 没有尚未激活/导航到.

This feels fragile, as the way I build the string is separate from the way the framework parses it. I would prefer for the framework to build me a string based on the current params, but $state.href('.') describes the current route, which doesn't include $stateParams that haven't yet been activated/navigated to.

我也看过 reloadOnSearch,但我认为它只适用于查询参数.

I've also looked at reloadOnSearch, but I think it only applies to query params.

有没有更好的建模方法?感觉就像我在为一些简单的事情与框架作斗争.

Is there a better way to model this? It feels like I'm fighting the framework over something simple.

推荐答案

您可以将状态参数传递给 $state.href 函数获取完整的 URL

You can pass state params to $state.href function to get the complete URL

$state.href('.', $stateParams)

要生成任意 url,您可以传递非当前参数和/或配置:

To generate arbitrary urls you can pass non-current params and/or configuration:

$state.href('.', {country:'usa',city:'sf'}, {absolute:true})

这篇关于在不重新加载页面的情况下更改 angular-ui-router 的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆