redben
redben

Reputation: 5696

How to have angular ui-router scroll to top before animation

When using ui-router with ngAnimate on ui-view, is there a way to make the scrolling happen before animation ?

Here is a plunkr where you can see that the animation happens before the scrolling, which looks awkward (at least to me...)

<!DOCTYPE html>
<html ng-app="myapp">

<head>
    <title>AngularJS: UI-Router Quick Start</title>
    <!-- Bootstrap CSS -->
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="animate.css" rel="stylesheet">
</head>

<body class="container">
  <p><i>Best viewed in pop-out mode to see location changes. Click blue button on the right.</i></p>

  <div class="navbar">
    <div class="navbar-inner">
      <a class="brand" href="#">Quick Start</a>
      <ul class="nav">
        <li><a href="#/foo">Route 1</a></li>
        <li><a href="#/bar">Route 2</a></li>
      </ul>
    </div>
  </div>

  <div class="row">
    <div class="span12 ui-view-container">
      <div class="well" ui-view></div>        
    </div>
  </div>         

  <!-- Angular -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
  <!-- Angular Animate -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular-animate.js"></script>
  <!-- UI-Router -->
  <script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>

  <!-- App Script -->
  <script>
    var myapp = angular.module('myapp', ["ui.router", "ngAnimate"])
    myapp.config(function($stateProvider, $urlRouterProvider){    
      $stateProvider
          .state("foo", {
              url: "/foo",
              templateUrl: 'foo'
          })
          .state("bar", {
              url: "/bar",
              template: '<h1>bar</h1>'
          })

      $urlRouterProvider.otherwise("/foo");
    })
  </script>

  <script type="text/ng-template" id="foo">
    <h1>Foo</h1>
    <p>this is a text that spreads below the fold<br>
    scroll all the way down and click the link <br>
    to go to route 2</p>
    <br><br><br><br><br><br><br>a little more to ensure it's bellow the fold<br><br><br><br><br><br><br>
    <br><br><br><br><br>You're nearly there....
    <br><br><br><br>When you click the link bellow to go to route2
    <br>Notice that the scrolling happens <br><b>after</b> the animation. 
    <br>
    <a href="#/bar">Route 2</a>
  </script>

</body>

</html>

Upvotes: 0

Views: 890

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

I'd love to get use of $anchorScroll() method of $anchorScroll service provided by angular, You should call the on $stateChangeStart event of angular ui-router

myapp.run(function($rootScope, $anchorScroll){
  $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    $anchorScroll();
  });
});

Working Plunkr

Upvotes: 1

Related Questions