- AngularJS provides $anchorScroll method to to jump to a location with specified id.
- AngularJS provides $location object with hash() method to replace the current URL with a given key string.
- $anchorScroll reads the hashed string and looks for the given id and jump to the section.
- In this demo, "We will implement the anchor scroll for given categories.When user click on the button the page focus moves to that section".
- Below HTML shows the HTML file rendering different categories and list of item under this.Using key values we have created the navigational button on the top.By clicking this button the focus moved to matched section with given id using anchor scroll object.
<!DOCTYPE html> <html ng-app="studentApp"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"> </script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-route.min.js"> </script> <meta charset="utf-8"> <title>AngularJS Anchor Scroll Example</title> </head> <body ng-controller="ItemController"> <button ng-repeat="(key, value) in terms" ng-click="jumpToLocation(key)"> {{key}} </button> <div ng-repeat="(key, value) in terms" id="{{key}}"> <h1>{{key}}<h1> <ol> <li ng-repeat="item in value"> {{item}} </li> </ol> </div> </body> </html>
- Below code shows the AngularJS script for the implementation of anchor scroll.
var studentApp = angular.module("studentApp",[]); //Using AnchorScroll studentApp.controller("ItemController", function ($scope, $location, $anchorScroll) { $scope.terms = { "fruits":["Apple","Mango","orange", "litchi","pears"], "flowers":["Rose","lily","jasmin", "lotus","sunflower"], "vegetables":["Potato","tomato","ladyfinger", "couliflower","cabbage"], "games":["Cricket","football","tennis", "baseball","hockey"], "countries":["India","America","China", "united kingdom","germany"] }; $scope.jumpToLocation = function(key){ $location.hash(key); $anchorScroll(); } });
- Code for the given demo is present in given JSBIN link.Output of the code is shown below with embedded bin.