AngularJS ui-router, scroll to next step on state change

Issue

I’m using UI-router in my app and I’d like to so a simple “scrollTo” to an anchor when the URL/state changes. I don’t want to load the next step from a template, or load a new controller. I’d just like several divs to be on the page already and scroll up and down between them. A simplified view of the HTML would be this.

    <div id="step1">
        <button ng-click="moveToStep2()">Continue</button>
    </div>
    <div id="step2">
        <button ng-click="moveToStep3()">Continue</button>
    </div>
    <div id="step3">
        Step 3 content
    </div>

So, when you enter the page the URL would be domain.com/booking

When you click the first button I’d like my controller code to change the URL to domain.com/#/step-2 and scroll down to the “step2” div.

Ideally, when the user hits the back button it would revert to the first URL and scroll back up to step 1.

Anybody know how to do this?

Solution

First. You need to define the state.

.state('step1', {
    url: '/step-1'
})

Add onEnter controller (so you can $inject things).

.state('step1', {
    url: '/step-1',
    onEnter: function () {}
})

Animate (or simply scroll) to element

$('html, body').animate({
    scrollTop: $("#step1").offset().top
}, 2000);

Here the example

Answered By – Umidbek Karimov

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.