ChatGPT解决这个技术问题 Extra ChatGPT

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?

As Alvaro Joao says below, you need to use angular-route.js in order to get this to work. bennadel.com/blog/…
Possible duplicate of AngularJs: Reload page

S
Scotty.NET

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.


Thanks for the comment, for some reason I seem to get slightly different behavior when I use $route.reload() compared to a normal refresh. For example a tab is set to show initially on refresh, but when the reload method seems to reload the page without setting the tab, not sure what the problem is.
Does this run filters/services as well? Getting undesired persistent state. Edit: Still upvoted for answering the question correctly & this is super helpful. Thank you
Remember to inject $route to the controller for this to work.
@alphapilgrim The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:
$state.reload() if you using stateProvider
d
danza

$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


It is worth noting that one shouldn't be storing state in the services anyway to require services to be "restarted".
Who says that? Where is one supposed to store cached data?
I have stumbled upon lots and lots of bugs due to data being stored in services, making them stateful rather than stateless. Unless we're talking about a caching service (in which case, there would be an interface to flush it), I would keep data out of services and in the controllers. For instance, one could keep data in localStorage, and use a service to access it. This would free the service from keeping data directly in it.
@danza Where is one supposed to store cached data? ... a model object? Howver Angular has done a terrible job of naming their MVCS constituents. I keep injectable model objects via the module.value API. Then the various APIs I defined on an ng service that alter the model object work more like commands.
Sure, that will work, but it is not good practice. See the documentation about $window, the reason for using it is explained in the beginning: While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing
K
Kumar Sambhav

For reloading the page for a given route path :-

$location.path('/path1/path2');
$route.reload();

Don't know why but the .reload() method seems not working here. It doesn't realod anything.
H
Hardik Vaghani

If you are using angular ui-router this will be the best solution.

$scope.myLoadingFunction = function() {
    $state.reload();
};

In my cli project after deployment to shared hosting. When i am reloading my project its giving 404 error to resolve this have used . If i add 'use hash', then it works with '#', but i don't want this , is there way it can be resolved.
M
Mario Medrano Maldonado

Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:

app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {   
   // $route.reload(); Then this should work fine.
}]);

V
Vaibs

Just to reload everything , use window.location.reload(); with angularjs

Check out working example

HTML

<div ng-controller="MyCtrl">  
<button  ng-click="reloadPage();">Reset</button>
</div>

angularJS

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.reloadPage = function(){window.location.reload();}
}

http://jsfiddle.net/HB7LU/22324/


t
trincot

If you want to refresh the controller while refreshing any services you are using, you can use this solution:

Inject $state

i.e.

app.controller('myCtrl',['$scope','MyService','$state', function($scope,MyService,$state) {

    //At the point where you want to refresh the controller including MyServices

    $state.reload();

    //OR:

    $state.go($state.current, {}, {reload: true});
}

This will refresh the controller and the HTML as well you can call it Refresh or Re-Render.


this is for ui router not for angular.
Y
Yamen Ashraf

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();

C
Community

Before Angular 2 ( AngularJs )

Through route

$route.reload();

If you want reload whole Application

$window.location.reload();

Angular 2+

import { Location } from '@angular/common';

constructor(private location: Location) {}

ngOnInit() {  }

load() {
    this.location.reload()
}

Or

constructor(private location: Location) {}

ngOnInit() {  }

Methods (){
    this.ngOnInit();
}

FYI - Angular 7: "Property 'reload' does not exist on type 'Location'".
@Cristina thanks your information. I use this before angular 7
d
diyoda_

Easiest solution I figured was,

add '/' to the route that want to be reloaded every time when coming back.

eg:

instead of the following

$routeProvider
  .when('/About', {
    templateUrl: 'about.html',
    controller: 'AboutCtrl'
  })

use,

$routeProvider
  .when('/About/', { //notice the '/' at the end 
    templateUrl: 'about.html',
    controller: 'AboutCtrl'
  })

@PardeepJain This worked for me. That is why this is an answer. Did you downvote my answer?
no not at all, your answer is not so bad to downvote. amazing i don't now why same is not working for me in angular2.
Perfect solution. Thks!
This works even if your original path is the root of the application - / :O My route now looks like this: //
In Angular 6 it works after using # same can be used for Angular2 too. think so
R
Ravi Mehta

I got this working code for removing cache and reloading the page

View

        <a class="btn" ng-click="reload()">
            <i class="icon-reload"></i> 
        </a>

Controller

Injectors: $scope,$state,$stateParams,$templateCache

       $scope.reload = function() { // To Reload anypage
            $templateCache.removeAll();     
            $state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
        };

K
KARTHIKEYAN.A

Use the following code without intimate reload notification to the user. It will render the page

var currentPageTemplate = $route.current.templateUrl;
$templateCache.remove(currentPageTemplate);
$window.location.reload();

J
Jose Ramon Leon Somovilla

I've had a hard fight with this problem for months, and the only solution that worked for me is this:

var landingUrl = "http://www.ytopic.es"; //URL complete
$window.location.href = landingUrl;

This is hardly different than doing $window.location.reload() which the OP specifically mentions does not work properly in his case.