How to reload or re-render the entire page using AngularJS
After rendering the entire page based on several user contexts and having made several $http
requests, I want the user to be able to switch contexts and re-render everything again (resending all $http
requests, etc). If I just redirect the user somewhere else, things work properly:
$scope.on_impersonate_success = function(response) {
//$window.location.reload(); // This cancels any current request
$location.path('/'); // This works as expected, if path != current_path
};
$scope.impersonate = function(username) {
return auth.impersonate(username)
.then($scope.on_impersonate_success, $scope.on_auth_failed);
};
If I use $window.location.reload()
, then some of the $http
requests on auth.impersonate(username)
that are waiting for a response get cancelled, so I can't use that. Also, the hack $location.path($location.path())
doesn't work either (nothing happens).
Is there another way to re-render the page without manually issuing all requests again?
For the record, to force angular to re-render the current page, you can use:
$route.reload();
According to AngularJS documentation:
Causes $route service to reload the current route even if $location hasn't changed.
As a result of that, ngView creates new scope, reinstantiates the controller.
$route.reload()
will reinitialise the controllers but not the services. If you want to reset the whole state of your application you can use:
$window.location.reload();
This is a standard DOM method which you can access injecting the $window service.
If you want to be sure to reload the page from the server, for example when you are using Django or another web framework and you want a fresh server side render, pass true
as a parameter to reload
, as explained in the docs. Since that requires interaction with the server, it will be slower so do it only if necessary
Angular 2
The above applies to Angular 1. I am not using Angular 2, looks like the services are different there, there is Router
, Location
, and the DOCUMENT
. I did not test different behaviors there
For reloading the page for a given route path :-
$location.path('/path1/path2');
$route.reload();