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

前端 未结 4 1705
攒了一身酷
攒了一身酷 2021-02-03 14:36

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

相关标签:
4条回答
  • 2021-02-03 14:42

    Using

    • $anchorScroll
    • and ui-router's onenter callback

    You can do something like this:

    $stateProvider.state("step1", {
      template: 'template.html',
      controller: ...,
      onEnter: function(){
          $location.hash('step1');
          $anchorScroll();
      }
    });
    ...
    
    0 讨论(0)
  • 2021-02-03 14:47

    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

    0 讨论(0)
  • 2021-02-03 14:48

    If the divs are already on the current page, just hard code the href to teh 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 讨论(0)
  • 2021-02-03 14:59

    You can listen to $locationChangeSuccess, e.g.

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

    Basic example: http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.$urlRouter

    0 讨论(0)
提交回复
热议问题