Angular ui-router, go to the next step to change state

I use a UI router in my application, and I would like a simple "scrollTo" to snap to the binding when the URL / state changes. I do not want to load the next step from the template or load a new controller. I would like for several divs to be on the page already and scroll up and down between them. This will be a simplified view of HTML.

<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 will be domain.com/booking

When you press the first button, I would like my controller code to change the URL to domain.com/#/step-2 and scroll down to the "step2" section.

Ideally, when a user clicks the back button, he returns to the first URL and scrolls back to step 1.

Does anyone know how to do this?

+6
source share
4 answers

Firstly. You need to determine the condition.

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

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

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

Animation (or just scrolling) to an element

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

Here is an example

+13
source

Using

You can do something like this:

 $stateProvider.state("step1", { template: 'template.html', controller: ..., onEnter: function(){ $location.hash('step1'); $anchorScroll(); } }); ... 
+8
source

You can listen to $locationChangeSuccess , for example

 $rootScope.$on('$locationChangeSuccess', scrollBasedOnLocationChangeEvent); 

Basic example: http://angular-ui.imtqy.com/ui-router/site/#/api/ui.router.router . $ urlRouter

+1
source

If the divs are already on the current page, just copy the href to the current

 <div id="step1"> <a href="wizard.html#/wizard/start#step1">Continue to step 1</a> </div> <div id="step2"> <a href="wizard.html#/wizard/start#step2">Continue step 2</a> </div> <div id="step3"> Step 3 content </div> <a name="#step2">STEP 2</a> <a name="#step1">STEP 1</a> 
0
source

Source: https://habr.com/ru/post/973319/


All Articles