I have a controller where I sometimes update the location using $location.search({param1: newParam1Value)
.
When I purposely change $location.search in the controller I would like to prevent a reload. Otherwise, I want to keep the default reloadOnSearch
behavior for this route/state.
I can set reloadOnSearch
to false when I define the state but then it will always be false.
Is there a way to toggle the reloadOnSearch
for the route from within the controller? Alternatively, can I keep reloadOnSearch: true
and just prevent reload some other way for the one instance where I don't want it to happen?
I am using ui.router
.
Yes!! you can use reloadOnSearch
conditionally. We know that state gets reloaded with $location.search() event. If your use case is like this, that in some case you want to reload state and in other case you don't, then use reloadOnSearch
like this:
$scope.myClickEvent = function () {
// prevent a reload
$state.current.reloadOnSearch = false;
$location.search('page', 2);
// Do your code...
loadData();
}
/* API call to load data */
var function loadData() {
// Do your code...
// Allow to reload state
$state.current.reloadOnSearch = undefined;
}
I needed this same functionality, and here's what I came up with:
As stated elsewhere, you need to turn reloadOnSearch = false
in the route. But MOST of the time, you want it to act like it used to with it set to true
. You just want to skip in certain circumstances. So I added this to my controller:
$rootScope.skipNextSearchChangeReload = false;
$scope.$on('$routeUpdate', function(){
if (!$rootScope.skipNextSearchChangeReload) {
$route.reload();
} else {
// skip reload, but reset to stop skipping
$rootScope.skipNextSearchChangeReload = false;
}
});
var updateSearchWithoutReload = function(key, values) {
$rootScope.skipNextSearchChangeReload = true;
$location.search(key, values);
};
then all changes to the url will still reload as usual. But when you want to skip the reload, you call updateSearchWithoutReload(key, values);
and it will skip for just that call. Then, after having skipped, it will reset to not skip reload.
I had tried just setting $rootScope.skipNextSearchChangeReload = true
and then $location.search(k, v)
and then $rootScope.skipNextSearchChangeReload = false
, but apparently the events hadn't propagated all the way through and skipNextSearchChangeReload
was set to false
before it had skipped. So this was the best I could come up with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With