Example Code - How to Use Angular.js Location Hash
2015/5/12 min read
bookmark this
How to scroll to the location on the page by Angular1
This quick code snippet shows how to use angular1 location hash to go to the specific section of the page. The framework is using angular1 1.4.8.
The Angular HTML
Following is the HTML for the angular, if the user click the gotoError link, will move to the error-placelocation.
<div ng-app="myApp" ng-controller="myController">
<div data-alert="" class="alert-box alert " id="error-place" ng-show="errors.length > 0">
<div ng-repeat="error in errors">
{{error}}
</div>
</div>
<div class="alert-box alert small-12 large-offset-3 large-9" ng-show="errors.length > 0">
<a ng-click="gotoError()" href='#'>Go to the Error</a>
</div>
</div>
The Angular Javascript
We'll create the angular controller as following, which will handler the click event when the user click the gotoError link. Also, this controller import Angular1 $anchorScroll, when this executed, it will scrolls to the hash value.
var app = angular.module('myApp', []);
app.controller("myController", ['$scope', '$location', '$anchorScroll', function($scope, $location, $anchorScroll){
$scope.errors = [
"I have more error1 to show!",
"I have more error2 to show!",
"I have more error3 to show!",
"I have more error4 to show!",
"I have more error5 to show!",
"I have more error6 to show!",
"I have more error7 to show!",
"I have more error8 to show!"
];
$scope.gotoError = function() {
$location.hash('error-place');
$anchorScroll();
}
}]);
Now, above is quick sample code of how to use location hash by angular1 way. You can also check the code at jsfiddler here.