How to reload or re-render the entire page using AngularJS
Asked Answered
S

13

311

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?

Surrey answered 22/5, 2013 at 23:28 Comment(2)
As Alvaro Joao says below, you need to use angular-route.js in order to get this to work. bennadel.com/blog/…Glarum
Possible duplicate of AngularJs: Reload pageVeldaveleda
S
410

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.

Surrey answered 29/5, 2013 at 18:54 Comment(10)
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.Hedge
is it possible to reload a specific controller that's not on the actual view or state?Barcellona
Does this run filters/services as well? Getting undesired persistent state. Edit: Still upvoted for answering the question correctly & this is super helpful. Thank youBaking
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, so they are instantiated once and never again.Surrey
Remember to inject $route to the controller for this to work.Arlin
any way to trigger this inline with a button?Nubia
@Surrey this gave me the following error, Unknown provider: $routeProvider <- $routeUnscramble
@Unscramble 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:Rocketry
$state.reload() if you using stateProviderRoanne
does this reload also trigger animations like ng-enter ?Marcum
P
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

Ploch answered 22/10, 2014 at 9:52 Comment(15)
It is worth noting that one shouldn't be storing state in the services anyway to require services to be "restarted".Surrey
Who says that? Where is one supposed to store cached data?Ploch
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.Surrey
@Ploch 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.Anodyne
just js method window.location.reload() without $ works for me.Febrifacient
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 testingPloch
But it won't redo template rendering in Django or other frameworks like Node.jsMihe
@AminahNuraini that should work, passing a parameter to reload. I edited the answer in order to include thatPloch
@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()´Mihe
@danza, $route is part of ng.route.IRouteService??Harlow
@Harlow ngRoute.$route.reload() in Angular 1.5Ploch
is that ngRoute.$route.reload() required any dependency too ?Arlynearlynne
@AnujGupta yes, obviouslyPloch
I tried that but it was generating some issues,I did my task from other method.ThanksArlynearlynne
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.Wolsky
G
39

For reloading the page for a given route path :-

$location.path('/path1/path2');
$route.reload();
Gearing answered 30/6, 2014 at 9:37 Comment(1)
Don't know why but the .reload() method seems not working here. It doesn't realod anything.Puissant
V
29

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

$scope.myLoadingFunction = function() {
    $state.reload();
};
Vladi answered 28/7, 2016 at 5:1 Comment(1)
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.Shawnna
K
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.
}]);
Khoisan answered 22/8, 2014 at 16:11 Comment(0)
P
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/

Predikant answered 17/1, 2016 at 18:11 Comment(0)
L
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.

Leggat answered 15/6, 2016 at 20:54 Comment(1)
this is for ui router not for angular.Dis
J
7

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();
Jurisdiction answered 31/10, 2018 at 13:31 Comment(0)
K
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();
}
Kaltman answered 23/7, 2018 at 8:38 Comment(2)
FYI - Angular 7: "Property 'reload' does not exist on type 'Location'".Dunleavy
@Cristina thanks your information. I use this before angular 7Kaltman
S
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'
  })
Shrewmouse answered 1/2, 2016 at 20:4 Comment(5)
@PardeepJain This worked for me. That is why this is an answer. Did you downvote my answer?Shrewmouse
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.Swindle
Perfect solution. Thks!Vltava
This works even if your original path is the root of the application - / :O My route now looks like this: //Suicidal
In Angular 6 it works after using # same can be used for Angular2 too. think soShawnna
B
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 });
        };
Beaufert answered 18/5, 2017 at 12:49 Comment(0)
V
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();
Varied answered 4/5, 2016 at 11:38 Comment(0)
P
-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;
Platus answered 14/1, 2015 at 12:53 Comment(1)
This is hardly different than doing $window.location.reload() which the OP specifically mentions does not work properly in his case.Haleigh

© 2022 - 2024 — McMap. All rights reserved.