310

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?

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
andersonvom
  • 11,701
  • 4
  • 35
  • 40
  • As Alvaro Joao says below, you need to use angular-route.js in order to get this to work. http://www.bennadel.com/blog/2770-route-must-be-injected-in-order-to-enable-the-routechangesuccess-event-in-angularjs.htm – Yvonne Aburrow Sep 15 '16 at 14:14
  • Possible duplicate of [AngularJs: Reload page](https://stackoverflow.com/questions/21885518/angularjs-reload-page) – Alena Kastsiukavets Aug 03 '17 at 12:57

13 Answers13

409

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.

Scotty.NET
  • 12,533
  • 4
  • 42
  • 51
andersonvom
  • 11,701
  • 4
  • 35
  • 40
  • 6
    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. – Doug Molineux May 28 '14 at 15:36
  • 1
    is it possible to reload a specific controller that's not on the actual view or state? – mautrok May 30 '14 at 10:12
  • 2
    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 – grant Nov 04 '14 at 20:15
  • As I mentioned in a comment below, you should persist data in the controllers and/or local storage only. Persisting data elsewhere, as you noticed, leads to these annoying bugs hard to fix. That happens because [they're singletons](https://docs.angularjs.org/guide/services#!), so they are instantiated once and never again. – andersonvom Nov 06 '14 at 12:04
  • 11
    Remember to inject `$route` to the controller for this to work. – Neel Jun 03 '15 at 18:37
  • any way to trigger this inline with a button? – JL Griffin Oct 09 '15 at 21:15
  • @andersonvom this gave me the following error, Unknown provider: $routeProvider <- $route – alphapilgrim Jan 29 '16 at 17:48
  • 6
    @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: – Alvaro Silvino Feb 04 '16 at 16:02
  • 3
    $state.reload() if you using stateProvider – Lalit Rao Apr 03 '17 at 11:06
  • does this reload also trigger animations like ng-enter ? –  Jun 19 '17 at 20:47
321

$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

danza
  • 11,511
  • 8
  • 40
  • 47
  • 2
    It is worth noting that one shouldn't be storing state in the services anyway to require services to be "restarted". – andersonvom Oct 22 '14 at 13:44
  • 20
    Who says that? Where is one supposed to store cached data? – danza Oct 23 '14 at 09:52
  • 6
    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. – andersonvom Oct 23 '14 at 14:07
  • 2
    @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. – jusopi Nov 14 '14 at 14:39
  • 1
    just js method `window.location.reload()` without `$` works for me. – Pranav Singh Aug 25 '15 at 09:50
  • 2
    Sure, that will work, but it is not good practice. See [the documentation about $window](https://docs.angularjs.org/api/ng/service/$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* – danza Sep 01 '15 at 08:23
  • But it won't redo template rendering in Django or other frameworks like Node.js – Aminah Nuraini Jun 02 '16 at 08:42
  • @AminahNuraini that should work, passing a parameter to `reload`. I edited the answer in order to include that – danza Jun 14 '16 at 13:43
  • @Danza, it turns out it didn't seem to rerender because the database API takes a little bit longer to update but I already reload. It was solved by putting the reload inside ´then()´ – Aminah Nuraini Jun 14 '16 at 13:47
  • @danza, $route is part of ng.route.IRouteService?? – cracker Jun 23 '16 at 10:25
  • @cracker `ngRoute.$route.reload()` in Angular 1.5 – danza Jul 14 '16 at 10:26
  • is that ngRoute.$route.reload() required any dependency too ? – Anuj Sep 12 '16 at 12:20
  • @AnujGupta yes, obviously – danza Sep 15 '16 at 11:08
  • I tried that but it was generating some issues,I did my task from other method.Thanks – Anuj Sep 16 '16 at 05:02
  • 1
    Thanks! I've just added a feature that displays a message in the ionCube24 UI for logged in users if we've just deployed an update and their UI code is now behind and needs refreshing; called from a function on the root scope, this works a treat to let the user trigger an update and reload of the application. – Nick Sep 25 '16 at 14:24
39

For reloading the page for a given route path :-

$location.path('/path1/path2');
$route.reload();
Kumar Sambhav
  • 7,503
  • 15
  • 63
  • 86
29

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

$scope.myLoadingFunction = function() {
    $state.reload();
};
Hardik Vaghani
  • 2,163
  • 24
  • 46
Neha DP
  • 291
  • 3
  • 3
  • 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. – T. Shashwat Jul 25 '18 at 11:40
24

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.
}]);
9

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/

Vaibs
  • 2,018
  • 22
  • 29
7

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Saurabh Sarathe
  • 231
  • 2
  • 11
7

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();
Yamen Ashraf
  • 2,637
  • 2
  • 20
  • 26
6

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();
}
Community
  • 1
  • 1
Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
5

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'
  })
diyoda_
  • 5,274
  • 8
  • 57
  • 89
4

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 });
        };
Ravi Mehta
  • 454
  • 1
  • 8
  • 20
3

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();
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
-9

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;