Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reload current route and reload the current template

Tags:

angularjs

When a use visits a private page unauthorized, say profile, my backend 302 redirects to a controller action that serves up the login partial in place of the profile partial. Since it 302 redirects to an action that returns a partial, the url address bar doesn't change from the page the user was trying to access ("/profile").

I was going to "fix" that but actually I think it makes a good user experience instead of dealing with return urls as query params.

The idea is once they log in I just want to reload the current route aka do a GET request for the profile partial via "/profile" and switch it back in instead of the login partial.

However, I can't get this "reload current route" to work. I tried all of the following:

$location.$$compose();
$location.absUrl($location.path());
$location.url($location.path());
$location.path($location.path())
$route.reload();

But none work. $route.reload() seems to be the definite way but it also doesn't work. It goes through the route cycle, reinstantiates the controller, but does not do GET request to reload the template

The only thing that works is a hard refresh via location.reload() but that is not ideal.

How can I force angular to reload the template for the current route?

like image 654
parliament Avatar asked Feb 16 '14 21:02

parliament


2 Answers

Ok I found the solution provided by lgalfaso on Github (exact paste):

Templates are cached, if a user does not have the permissions to be in a page, then this check should be done before it reaches the controller or after, within the controller, but not on the template retrieval

If this is the way you want to follow, then you need to remove the template from the $templateCache before you call reload

So that worked for me because login template actually gets cached as the template the user was trying to access. So removing it and letting angular re-fetch the correct one for the current route worked like a charm.

var currentPageTemplate = $route.current.templateUrl;
$templateCache.remove(currentPageTemplate);
$route.reload();
like image 86
parliament Avatar answered Sep 28 '22 02:09

parliament


I have noticed that $route.reload() method re-instantiates everything that is setup on your $routeProvider.when("/someUrl",{controller:'SomeController',templateUrl:'SomeView.html'}) template,controller and/or any resolved promises you may have passed within the .when() method.

Therefore; when you build your app, if you want $route.reload() to reload all the page and re-instantiate controllers you must put everything under your <div ng-view></div> container and include any menus or footers inside the templateUrl file.

like image 29
Logus Graphics Avatar answered Sep 28 '22 03:09

Logus Graphics