Most of the case you can use
$window.scrollTo(x, y);
Where scrollTo takes x,y coordinates.
// Optional: focus the alert for accessibility angular.element(document.querySelector('.alert'))
.attr('tabindex', '-1').focus();
Just add window.scrollTo(0, 0) after receiving your AJAX response to scroll the page to the top. For better accessibility, you can also focus the alert element by adding tabindex=”-1″ and calling .focus() on it.
There are other methods to achieve this as follows
// Method 1: Using $anchorScroll service: Angular’s built-in service for handling scrolling to specific elements. Add an element with id=”top” at the top of your page.
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', '$location', '$anchorScroll',
function($scope, $http, $location, $anchorScroll) {
$scope.getData = function() {
$http.get('/api/endpoint').then(function(response) {
$scope.alertMessage = "Success!";
// Set the hash and scroll
$location.hash('top');
$anchorScroll();
});
};
}
]);
// Method 2: Using $document service: For animated scrolling to top.
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', '$document',
function($scope, $http, $document) {
$scope.getData = function() {
$http.get('/api/endpoint').then(function(response) {
$scope.alertMessage = "Success!";
// Animate scroll to top
$document.scrollTopAnimated(0, 400); // 400ms duration
});
};
}
]);
// Method 3: Using a custom directive: Make a reusable directive for scrolling functionality.
angular.module('myApp', [])
.directive('scrollToTop', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth' // Smooth scrolling
});
});
}
};
})
.controller('MyController', ['$scope', '$http',
function($scope, $http) {
$scope.getData = function() {
$http.get('/api/endpoint').then(function(response) {
$scope.alertMessage = "Success!";
// Trigger scroll through event or directly
angular.element(document.querySelector('.scroll-top-btn')).triggerHandler('click');
});
};
}
]);
// Method 4: Using a service: Create a dedicated service to handle scrolling behavior across your app.
angular.module('myApp', [])
.service('ScrollService', [function() {
return {
scrollToTop: function(duration) {
var scrollStep = -window.scrollY / (duration / 15);
var scrollInterval = setInterval(function() {
if (window.scrollY !== 0) {
window.scrollBy(0, scrollStep);
} else {
clearInterval(scrollInterval);
}
}, 15);
}
};
}])
.controller('MyController', ['$scope', '$http', 'ScrollService',
function($scope, $http, ScrollService) {
$scope.getData = function() {
$http.get('/api/endpoint').then(function(response) {
$scope.alertMessage = "Success!";
// Use the service
ScrollService.scrollToTop(300); // 300ms duration
});
};
}
]);
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers