如何在HTML中使用使用锚与UI路由器

如何在HTML中使用使用锚与UI路由器

问题描述:

我用角UI路由器,就像如何在HTML中使用使用锚与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”,将URL http://localhost:8000/dist/#/aaa 并返回home.html的空白PAGE电泳锚不起作用。

我该如何解决这个问题?

+0

你想要发生什么?重定向到外部网站?或者在你的应用程序中的默认路线? – henrikmerlander

这不是UI路由器问题,这是因为base标记。 您应该在#id之前的href中添加当前页面路径。 试试这个:(我没有测试过)

<a ui-sref="state_of_current_page" href="#your_id">link to id</a> 

资源: tutsplus article about base tag related question in SO

+1

我按照您的建议尝试过.' link to foo'但是,它不起作用。 – PurpleCraw

请确保您有一个UI路由器版本比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.html的

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

使用ui-SREF以及href标签。 href用于指向页面的本地ID。 ui-sref应指向同一页面的状态。例如,

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

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

使用语法如

ui-sref="home({'#': 'aaa'})" 

将导致做工作,但将哈希添加到URL。这在使用其他框架(如jQuery)时也会产生语法错误。