Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use use anchor in html with ui router

I used angular ui router, just like

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

and I can visit in browser with a url, http://localhost:8000/dist/#/home However, I can not use a anchor in my html if there is a anchor in home.html like this

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

when I click "scroll to aaa", the url will be http://localhost:8000/dist/#/aaa and return a blank page.The anchor in home.html does not work.

How can I resolve this problem?

like image 973
PurpleCraw Avatar asked Mar 28 '16 14:03

PurpleCraw


2 Answers

Make sure you have a ui-router version newer than 0.2.14, which was the first version to support html anchors in ui-router. All versions can be found on github, where I first noticed that it was supported.

Given your routing setup:

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

Create a link on any view:

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

On page view/home/home.html

....
....
<h1 id="aaa">AAA</h1>
like image 168
Fredrik Avatar answered Nov 20 '22 21:11

Fredrik


Use ui-sref along with the href tag. The href is used to point the local id of the page. And the ui-sref should point to the state of the same page. For example,

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

This will make the page scroll to the requires element without adding anything to your url.

Using syntaxes such as

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

will result in doing the job but will add the hash to the url. This would also produce syntax error when you're using other frameworks such as jQuery.

like image 31
Shiva Sairam M Avatar answered Nov 20 '22 23:11

Shiva Sairam M