Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to conditionally turn off reloadOnSearch in a controller?

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.

like image 577
Justin Avatar asked Mar 06 '14 00:03

Justin


2 Answers

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;
}
like image 133
Rubi saini Avatar answered Nov 15 '22 12:11

Rubi saini


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.

like image 30
Cameron Avatar answered Nov 15 '22 14:11

Cameron