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.
$timeout($anchorScroll())
? – Validate$timeout
just hang out so it's executed when it's loaded. The hash should already be in the URL. – Validate$rootScope.$on
to the$timeout
it should work, assuming your url is being set properly. I'm working on a plunker, but this kind of problem isn't suited for that environment. – Validate