I need to set an ng-click event so that that it loads a new page, and then, once the page has loaded, scrolls to an anchor point on the page. I've tried every solution proposed on this SO post but I can't get it to work correctly.
Most of those solutions center around scrolling to an anchor on a page that's already loaded. I need the scroll to occur after a new page has loaded.
Here is my view code:
<div class="see-jobs-btn" ng-click="$event.stopPropagation();goToResultJobs(r)">See Jobs</div>
This represents a button inside a 'profile card'. When the user clicks on the card, it takes them to a profile page. However, when they click the button, it needs to take them to the #jobs portion of that profile page (hence the $stopPropogation() before the goToResultJobs(r) in the code).
Here is what my goToResultJobs method looks like.
$scope.goToResultJobs = function(result) {
var profileUrl = result.slug;
window.location = profileUrl;
};
I've tried using $anchorScroll
and just hardcoding in the anchor into the profileUrl
, but neither one works. I'm fairly new to Angular, so I don't know what I'm missing here.
UPDATE 1: Trying to use $timeout
Here is my goToResultJobs
method within my ResultsCtrl that is triggered when the user clicks the button:
$scope.goToResultJobs = function(result) {
var url = window.location + result.slug + '#jobs';
location.replace(url);
};
That loads the /name#jobs
path, which calls the ProfileCtrl below:
app.controller('ProfileCtrl', ['$scope', '$http', '$timeout', '$location', '$anchorScroll',
function($scope, $http, $timeout, $location, $anchorScroll) {
if(window.location.hash) {
$timeout(function() {
console.log('TEST');
// $location.hash('jobs');
// $location.hash('jobs');
$anchorScroll();
}, 1000);
};
}]);
This setup seems to work, as TEST
only appears in the console when the jobs button is clicked, but not when the user just clicks on the profile. The problem I'm now facing is that the page starts loading, and the path in the url bar changes to /name#jobs
, but before the page finishes loading, jobs
is stripped from the url. Therefore, when $anchorScroll()
is called, there is no anchor tag in the hash to scroll to.
So as pointed out, the $anchorScroll
has to occur after the page has been rendered, otherwise the anchor doesn't exist. This can be achieved using $timeout()
.
$timeout(function() {
$anchorScroll('myAnchor');
});
You can see this plunkr. Make sure to view it in pop-out mode (the little blue button in the upper right corner of the output screen).