Search code examples
angularjsangularjs-material

duScrollTop not working


I have the following code, but the scrolling does not work.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-scroll/1.0.2/angular-scroll.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<body>
  <div style="width: 100%; height: 120vh;">EXAMPLE</div>
  
  <footer>
    <button ng-click="scrollToTop()">To the top!</button>
  </footer>
<script>
angular.module('myApp', ['duScroll']).
  controller('MyCtrl', ['$scope', '$document', function($scope, $document){

    $scope.scrollToTop = function() {
      $document.duScrollTop();
    };

  }]);
</script>
</body>
</html>

The method duScrollTop() does not work for me.


Solution

  • 1) You $scope.scrollToTop method is declared within MyCtrl, so you have to use ngController directive to allow using this method with ngClick;

    2) Simply calling scrollTop() will return current scroll position; to scroll to specified position you have to pass arguments to this method:

    .scrollTop|scrollLeft( top [, duration [, easing ] ] )

    Scrolls to specified position in either axis, with optional animation.

    Here is a working example:

    angular.module('myApp', ['duScroll']).
    controller('MyCtrl', ['$scope', '$document', function($scope, $document){
      $scope.scrollToTop = function() {
        $document.duScrollTop(0);
      };
    }]);
    <!DOCTYPE html>
    <html ng-app="myApp" ng-controller="MyCtrl">
    <body>
      <div style="width: 100%; height: 120vh;">EXAMPLE</div>
      <footer>
        <button ng-click="scrollToTop()">To the top!</button>
      </footer>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-scroll/1.0.2/angular-scroll.min.js"></script>
    </body>
    </html>