How to reload the current state? - angularjs

I'm using Angular UI Router and would like to reload the current state and refresh all data / re-run the controllers for the current state and it's parent.
I have 3 state levels: directory.organisations.details
directory.organisations contains a table with a list of organisations. Clicking on an item in the table loads directory.organisations.details with $StateParams passing the ID of the item. So in the details state I load the details for this item, edit them and then save data. All fine so far.
Now I need to reload this state and refresh all the data.
I have tried:
$state.transitionTo('directory.organisations');
Which goes to the parent state but doesn't reload the controller, I guess because the path hasn't changed. Ideally I just want to stay in the directory.organisations.details state and refresh all data in the parent too.
I have also tried:
$state.reload()
I have seen this on the API WIKI for $state.reload "(bug with controllers reinstantiating right now, fixing soon)."
Any help would be appreciated?

I found this to be the shortest working way to refresh with ui-router:
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams
Update for newer versions:
$state.reload();
Which is an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
Documentation: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_reload

This solution works in AngularJS V.1.2.2:
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});

That would be the final solution. (inspired by #Hollan_Risley's post)
'use strict';
angular.module('app')
.config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});
Now, whenever you need to reload, simply call:
$state.forceReload();

for ionic framework
$state.transitionTo($state.current, $state.$current.params, { reload: true, inherit: true, notify: true });//reload
$stateProvider.
state('home', {
url: '/',
cache: false, //required
https://github.com/angular-ui/ui-router/issues/582

Probably the cleaner approach would be the following :
<a data-ui-sref="directory.organisations.details" data-ui-sref-opts="{reload: true}">Details State</a>
We can reload the state from the HTML only.

#Holland Risley 's answer is now available as an api in latest ui-router.
$state.reload();
A method that force reloads the current state. All resolves are
re-resolved, controllers reinstantiated, and events re-fired.
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state

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

$scope.reloadstat = function () { $state.go($state.current, {}, {reload: true}); };

if you want to reload your entire page, like it seems, just inject $window into your controller and then call
$window.location.href = '/';
but if you only want to reload your current view, inject $scope, $state and $stateParams (the latter just in case you need to have some parameters change in this upcoming reload, something like your page number), then call this within any controller method:
$stateParams.page = 1;
$state.reload();
AngularJS v1.3.15
angular-ui-router v0.2.15

Silly workaround that always works.
$state.go("otherState").then(function(){
$state.go("wantedState")
});

For angular v1.2.26, none of the above works. An ng-click that calls the above methods will have to be clicked twice in order to make the state reload.
So I ended up emulating 2 clicks using $timeout.
$provide.decorator('$state',
["$delegate", "$stateParams", '$timeout', function ($delegate, $stateParams, $timeout) {
$delegate.forceReload = function () {
var reload = function () {
$delegate.transitionTo($delegate.current, angular.copy($stateParams), {
reload: true,
inherit: true,
notify: true
})
};
reload();
$timeout(reload, 100);
};
return $delegate;
}]);

Everything failed for me. Only thing that worked...is adding cache-view="false" into the view which I want to reload when going to it.
from this issue https://github.com/angular-ui/ui-router/issues/582

Not sure why none of these seemed to work for me; the one that finally did it was:
$state.reload($state.current.name);
This was with Angular 1.4.0

I had multiple nested views and the goal was to reload only one with content.
I tried different approaches but the only thing that worked for me is:
//to reload
$stateParams.reload = !$stateParams.reload; //flip value of reload param
$state.go($state.current, $stateParams);
//state config
$stateProvider
.state('app.dashboard', {
url: '/',
templateUrl: 'app/components/dashboard/dashboard.tmpl.html',
controller: 'DashboardController',
controllerAs: 'vm',
params: {reload: false} //add reload param to a view you want to reload
});
In this case only needed view would be reloaded and caching would still work.

I know there have been a bunch of answers but the best way I have found to do this without causing a full page refresh is to create a dummy parameter on the route that I want to refresh and then when I call the route I pass in a random number to the dummy paramter.
.state("coverage.check.response", {
params: { coverageResponse: null, coverageResponseId: 0, updater: 1 },
views: {
"coverageResponse": {
templateUrl: "/Scripts/app/coverage/templates/coverageResponse.html",
controller: "coverageResponseController",
controllerAs: "vm"
}
}
})
and then the call to that route
$state.go("coverage.check.response", { coverageResponse: coverage, updater: Math.floor(Math.random() * 100000) + 1 });
Works like a charm and handles the resolves.

You can use #Rohan answer https://stackoverflow.com/a/23609343/3297761
But if you want to make each controller reaload after a view change you can use
myApp.config(function($ionicConfigProvider) { $ionicConfigProvider.views.maxCache(0); ... }

If you are using ionic v1, the above solution won't work since ionic has enabled template caching as part of $ionicConfigProvider.
Work around for that is a bit hacky - you have to set cache to 0 in ionic.angular.js file:
$ionicConfigProvider.views.maxCache(0);

I had this problem it was wrecking my head, my routing is read from a JSON file and then fed into a directive. I could click on a ui-state but I couldn't reload the page. So a collegue of mine showed me a nice little trick for it.
Get your Data
In your apps config create a loading state
Save the state you want to go to in the rootscope.
Set your location to "/loading" in your app.run
In the loading controller resolve the routing promise and then set the location to your intended target.
This worked for me.
Hope it helps

Related

reload: true works only once

I am trying to pass parameters from one view to another in my anulgar/ionic app.
in the volCompute view ($stateParams is declared):
if ($stateParams.modelLine){
console.log('receiving', $stateParams.modelLine.id, $stateParams.modelLine.modelStrict)
$scope.data.chosenModel = $stateParams.modelLine.modelStrict;
}
in the compareview:
$state.go('app.volCompute', { modelLine: test[0] }, {reload: true});
but it works only one time, if I go back and forth between the two views the code in volCompute is not run.
It seems like the reload: true is only executed once.
Can you help please ?
There are few more details how to understand ionic caches
What is the difference between $ionicView.enter and cache:false
ui.router not reloading controller
And I would suggest to use the event hook here $ionicView.enter or $ionicView.afterEnter
$scope.$on('$ionicView.enter', function(){
// Coding
});
there is the link to doc
In your routes file:
$stateProvider.state('myState', {
cache: false,
url : '/myUrl',
templateUrl : 'my-template.html'
})
Or inidividually in an <ion-view> tag:
<ion-view cache-view="false">
...
</ion-view>

Force reload route/state on link click

Currently I'm doing something like this
link.on('click', function () {
if (link.attr('href') !== $route.current.originalPath)
return;
$route.reload();
});
I'm not aware of side effects but I guess there can be some.
Is there more straightforward way to handle this in ngRoute, e.g. through $location?
What is the way to do the same thing in UI Router when the app will be updated to use it?
With UI-Router we have a set of options, and one of them is {reload: true}
go(to, params, options)
location - {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace",
which will update url and also replace last history record.
inherit - {boolean=true}, If true will inherit url parameters from current url.
relative - {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from.
notify - {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events.
reload (v0.2.5) - {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same
state. It differs from reloadOnSearch because you'd use this when you
want to force a reload when everything is the same, including search
params.
So we can force state reload with:
$state.go("stateName", stateParams, {reload: true});
Your code could get tranformed to below change $route.reload() to $state.reload()
Code
link.on('click', function () {
if (link.attr('href') !== $route.current.originalPath)
return;
//though this will not reload the controller content
$state.reload(); //will force to reload state..
$scope.$apply(); //needed here to tell angular js to run digest cycle.
});
From git-hub issue it seems like $state.reload() reload the state but controller doesn't get re-instantiate. For that you need to use below code instead of $state.reload()
$state.transitionTo('tab.locations', $state.$current.params, {
reload: true, inherit: true, notify: true
});
I found this to be the shortest way with UI-router :
$state.go($state.current, {}, {reload: true});
or you can do this :
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
If you are using Ui.Router:
link.on('click', function (event) {
if (link.attr('href') !== $route.current.originalPath)
return;
event.preventDefault();
return $scope.$apply(function() {
return $state.reload(); // $state.go($state.current.name, $stateParams, { inherit: false, reload: true, notify: true });
});
});
If you are using the simply ngRoute, you must to remove your the currentTemplate from templateCache and the return $route.reload() in a $timout!

How to reload AngularJS controller and resolver?

I am using Angular's UI Router and I am looking to create a $scope function (ultimately to pass to the view to have a ng-click call it) to reload a controller and its associated resolver. How would I do this?
I've tried this but it doesn't seem to reload the resolver:
$scope.reloadMe = function() {
$state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
};
just inject $route into the controller and call $route.reload so the code would look like:
$scope.reloadMe = function () {
$route.reload();
};
You can read the documentation here: https://docs.angularjs.org/api/ngRoute/service/$route
You can inject $injector and load $state to reload. Here I put two examples, you can use one of them.
function MyController($injector, data) {
$injector.get('$state').reload(); // this reload all states and controllers scopes
// or
$injector.get('$state').go($state.current, {}, {reload: true}); // second parameter is for $stateParams
}
Otherwise, in case i need to reload the page, i use javascript
window.location.reload()
This question is asked here

AngularJS ui-router: force reload

I have an AngularJS app starting at index.html and using ui-router. Based on a trigger I want to reload the complete page. I tried:
$state.go($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
But that does not work. It doesn't reload my initial index.html.
I can do:
window.location.href = "index.html";
But then I'm on my initial page, not the current state.
Should a set window.location.href to index.html with query string parameters specifying current location? If I do that, how can I navigate to this location?
The current trick is:
$state.go($state.current.name, $state.params, { reload: true });
Everybody seems to have ignored what Serge van den Oever appears to actually be asking, and that's that he wants entire page to reload, and not just the route.
The solution for that is pretty simple if you inject the $window service into your controller:
$window.location.reload();
If you just want the route to reload (which seems to be much more common), and are using ui-router, then just inject the $state service and do:
$state.reload();
This should reinitialize controllers now that the bug has been fixed, although I don't think it reinitializes resolves.
This worked for me in a similar scenario.
$state.go('root.state').then(function(){
$state.reload();
});
If you include the $route service in your controller you could try $route.reload();
Try this:
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});

AngularJS ui-router state doesn't refresh on back

I have an app setup with 2 states, A and A.B done this way:
$stateProvider.state('A', {
url: "/A/{aId}",
controller: 'AController',
templateUrl: function($stateParams) {
return "/A/" + $stateParams.aId + "/layout";
}
}).state('A.B', {
url: "/B/{bId}",
controller: 'BController',
templateUrl: function($stateParams) {
return "/A/" + $stateParams.aId + "/B/" + $stateParams.bId+ "/layout";
}
});
When I'm in state A.B ( the url would be somthing like #/A/12/B/123 ) and go back using the back button of the browser or transitionTo the url changes, state A.B is cleared but state A doesn't render back. As far as I can tell the controller isn't triggered.
So if I'm in A/12/B/123 and go back to A/12 nothing happens, but if I go back to A/13 ( using transitionTo ) it renders.
On the sample app from angular-ui-router project this scenario works fine, so I think there might be something wrong in my setup. I think it's worth mentioning that on index.html I have a ui-view which loades state A and the template for state A has another ui-view that loads state A.B
If anyone could help, I would really appreciate it
Have you tried using this:
$state.reload()
Its a method that force reloads the current state. All resolves are re-resolved, events are not re-fired, and controllers reinstantiated
This is just an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: false
});

Resources