Sample app: http://angular.github.com/angular-phonecat/step-11/app/#/phones
If you choose the last phone \"Motorola charm\" it will show you the details of the phone
If your page requires fetching of data to display, you may have to use $routeChangeSuccess and delay the scrolling function call.
scope.$on("$routeChangeSuccess", function() {
$timeout(function () {
var scrollY = parseInt(scope.$eval(attrs.ngKeepScroll));
$(window).scrollTop(scrollY ? scrollY : 0);
}, 1000); // delay by 1 sec
});
For those of you that went with emp's answer, but were using angular ui-router >= version 1.0.0 (current 1.0.3), please see his directive rewritten, using ui-routers new transitions.
HTML
<div ui-view keep-scroll-pos></div>
Angular Directive
angular.module("app")
.directive("keepScrollPos", function($transitions, $state, $window, $timeout, $location, $anchorScroll) {
// cache scroll position of each state's templateUrl
var scrollPosCache = {};
return {
link: function(scope, element, attrs) {
$transitions.onStart({ }, function( trans ) {
// store scroll position for the current view
if (trans.from().name) {
scrollPosCache[trans.from().templateUrl] = [ $window.pageXOffset, $window.pageYOffset ];
}
trans.promise.finally(function () {
// if hash is specified explicitly, it trumps previously stored scroll position
if ($location.hash()) {
$anchorScroll();
// else get previous scroll position; if none, scroll to the top of the page
} else {
var prevScrollPos = scrollPosCache[trans.to().templateUrl] || [ 0, 0 ];
$timeout(function() {
$window.scrollTo(prevScrollPos[0], prevScrollPos[1]);
}, 200);
}
});
});
}
}
});
You need to reset the scroll position on each route change. Use this in your main AppController:
$scope.$on("$routeChangeSuccess", function () {
$anchorScroll();
});
Or if you are using ui-route:
$scope.$on("$stateChangeSuccess", function () {
$anchorScroll();
});
For more infomation see In AngularJS, how do I add a $watch on the URL hash?