Monday, October 10, 2016

AngularJS - Service - $anchorScroll

Used for making the view to jump to a specified element on the page.

Example: Making a long page to scroll top or bottom based on the "Got to Bottom of the Page" and "Go to Bottm of the Page".

Define Controller: controller.js
var myApp = angular.module("myApp", [])
                                   .controller('myController', function($scope, $location, $anchorScroll){
                                          $scope.scrollTo = function (scrollLocation) {
                                                 $location.hash(scrollLocation);
                                                 $anchorScroll();
                                          }

                                      });

Use controller in the HTML page: mypage.html
<div ng-controller='myController'>
              <div>
                       <button  id="top" ng-click="scrollTo=('top')" value ="Go to Bottom of the Page />
                         
                       <!-- some lengthy data. -->
                        
                        <button id="bottom"  ng-click="scrollTo('bottom')" value ="Go to Top of the Page />
              </div>    

    </div>

In the example above the parameter scrollLocation holds the id of the button based on the button which is invoked. The hash method of $location service appends the hash fragment to the URL. In our case is is either "#top" or "#bottom" based on the scrollLocation parameter value. The $anchorScroll method reads the hashed fragment from the URL and automatically scrolls to the that element of the page. 

No comments:

Post a Comment