gpt4 book ai didi

angularjs - UI Router 匹配 url 和哈希(片段)

转载 作者:行者123 更新时间:2023-12-05 05:25:43 25 4
gpt4 key购买 nike

使用 UI 路由器,我需要将 URL 与其中包含的哈希(片段)相匹配(HTML5 模式)。

.state('myState', {
url: '/path/:id/page#:section',
templateUrl: 'template.html',
controller: 'MyController'
});

虽然上面的设置在使用下面的 ui-sref 时有效..

<a ui-sref="myState({id: 1})"> ... // without hash => section == ''
<a ui-sref="myState({id: 1, section: 'abc'})"> ... // section == 'abc'

.. 当我通过在地址栏中指定片段手动从其他页面重定向浏览器时失败(或者当在完全不同的站点上单击包含哈希的链接时)在这种情况下,URL 匹配器尝试匹配 URL 而没有哈希和我被迫创建一个新的人工状态,它与上面相同但没有哈希和它的 url 属性中的参数 section。但这让我不可能拥有包含哈希的可收藏 URL。

我需要一个状态,其中这个片段参数是可选的,并且在重定向到保留给定 section 参数的页面时通过应用内状态转换和 url 匹配机制正确匹配(如果现在)。

最佳答案

我通过使用 # 参数解决了这个问题:

<a ui-sref="myState({id: 1})"> ... // without hash => # == ''
<a ui-sref="myState({id: 1, '#': 'abc'})"> ... // # == 'abc'

状态定义中的 URL 完全没有哈希:

url: '/path/:id/page',

这将页面加载时的状态与 URL 中的哈希匹配,但是它仍然没有在状态参数中设置 # 值。我通过在 $stateChangeStart 事件处理程序中手动设置参数来解决此问题:

 $rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
var hash = $location.hash();
if (hash) {
toParams['#'] = hash;
}
}

关于angularjs - UI Router 匹配 url 和哈希(片段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30169303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com