【问题标题】:how to use use anchor in html with ui router如何在带有ui路由器的html中使用锚点
【发布时间】:2018-01-13 22:09:58
【问题描述】:

我使用了angular ui路由器,就像

.state('home', {
        url: '/home',
        templateUrl: 'view/home/home.html',
        controller: 'homeCtrl'
    })
.state('guide', {
        url: '/guide',
        templateUrl: 'view/guide/guide.html',
        controller: 'guideCtrl'
    })

我可以在浏览器中使用 url http://localhost:8000/dist/#/home 访问 但是,我不能在我的 html 中使用锚点 如果 home.html 中有这样的锚

<a href="#aaa">scroll to aaa</a>
....
<h1 id="aaa">AAA</h1>

当我点击“滚动到 aaa”时,网址将是 http://localhost:8000/dist/#/aaa 并返回一个空白页。home.html 中的锚点不起作用。

我该如何解决这个问题?

【问题讨论】:

  • 你想要发生什么?重定向到外部网站?还是到您应用程序中的默认路由?

标签: angular-ui-router anchor


【解决方案1】:

确保您的 ui-router 版本比 0.2.14 更新,这是第一个在 ui-router 中支持 html 锚点的版本。所有版本都可以在on github找到,我第一次注意到it was supported

鉴于您的路由设置:

.state('home', {
    url: '/home',
    templateUrl: 'view/home/home.html',
    controller: 'homeCtrl'
})
.state('guide', {
    url: '/guide',
    templateUrl: 'view/guide/guide.html',
    controller: 'guideCtrl'
})

在任何视图上创建链接:

<a href="" ui-sref="home({'#': 'aaa'})">Scroll to AAA</a>

在页面视图/home/home.html

....
....
<h1 id="aaa">AAA</h1>

【讨论】:

  • 你知道这个答案是否仍然是最新的。我已经尝试过了,但它对我不起作用:stackoverflow.com/questions/70893870/…
  • 我不确定它是否仍然是最好的解决方案。我知道它至少在那时有效。也许取决于正确的 ui-router-version?
【解决方案2】:

使用 ui-sref 和 href 标签。 href 用于指向页面的本地 id。并且 ui-sref 应该指向同一页面的状态。例如,

<a href="myId" ui-sref="stateOfCurrentPage"> any Link </a>

这将使页面滚动到 requires 元素,而不向您的 url 添加任何内容。

使用诸如

之类的语法
ui-sref="home({'#': 'aaa'})"

将导致完成这项工作,但会将哈希添加到 url。当您使用 jQuery 等其他框架时,这也会产生语法错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2018-08-03
    • 2016-06-22
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多