angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Option on $location to allow hash/path change w/o reloading the route

Open cgross opened this issue 13 years ago • 194 comments

We have a paradigm in our app that user's create new things on the same page that they view things. So our route is like /thing/:id. When creating a new thing they go to /thing/new. Once the thing has been successfully saved we want to change the route to /thing/1234 (or whatever its new id is). Now the partial doesnt need to be reloaded because the data is all the same. We just want the path to be updated so a user can now bookmark the correct link, etc.

Having an option on $location (not on the route definition) to enable/disable route loading would work but I'm sure there are other ways to implement the feature.

cgross avatar Dec 12 '12 18:12 cgross

Edit: better approach here: https://github.com/angular/angular.js/issues/1699#issuecomment-22511464

I've created a reusable factory to bypass this (based on the idea from @shahmirn):

/**
 * HACK Do not reload the current template if it is not needed.
 *
 * See AngularJS: Change hash and route without completely reloading controller http://stackoverflow.com/questions/12115259/angularjs-change-hash-and-route-without-completely-reloading-controller
 */
app.factory('DoNotReloadCurrentTemplate', ['$route', function($route) {
  return function(scope) {
    var lastRoute = $route.current;
    scope.$on('$locationChangeSuccess', function() {
      if (lastRoute.$$route.templateUrl === $route.current.$$route.templateUrl) {
        console.log('DoNotReloadCurrentTemplate not reloading template: ' + $route.current.$$route.templateUrl);
        $route.current = lastRoute;
      }
    });
  };
}]);

How to use:

app.controller('MyCtrl',
  ['$scope', 'DoNotReloadCurrentTemplate',
  function($scope, DoNotReloadCurrentTemplate) {

  DoNotReloadCurrentTemplate($scope);
}]);

Source: http://stackoverflow.com/a/16496112/990356

tkrotoff avatar Jun 27 '13 23:06 tkrotoff

If you set "reloadOnSearch" to false on the route then it seems to fix the hash changes reloading the whole page.

zariel avatar Jul 10 '13 21:07 zariel

+1

This would be great for mobile apps, where the ng-view create/destroy lifecycle is not appropriate (kills performance and usability).

mgcrea avatar Jul 11 '13 23:07 mgcrea

@tkrotoff Thanks for the example. Since your workaround is cancelling event notifications I've added a broadcast on the rootscope so other controllers can still be notified of the route change:

/**
 * HACK Do not reload the current template if it is not needed.
 *
 * See AngularJS: Change hash and route without completely reloading controller http://stackoverflow.com/questions/12115259/angularjs-change-hash-and-route-without-completely-reloading-controller
 */
app.factory('DoNotReloadCurrentTemplate', ['$route', '$rootScope', function($route, $rootScope) {
  return function(scope) {
    var lastRoute = $route.current;
    scope.$on('$locationChangeSuccess', function() {
      if (lastRoute.$$route.templateUrl === $route.current.$$route.templateUrl) {
        console.log('DoNotReloadCurrentTemplate not reloading template: ' + $route.current.$$route.templateUrl);
        $rootScope.$broadcast('locationChangedWithoutReload', $route.current);
        $route.current = lastRoute;        
      }
    });
  };
}]);

Then:

app.controller('MyCtrl',
  ['$scope', 'DoNotReloadCurrentTemplate',
  function($scope, DoNotReloadCurrentTemplate) {

  DoNotReloadCurrentTemplate($scope);

  $rootScope.$on('locationChangedWithoutReload', function(event, route) {
    // set location specific breadcrumbs
    $scope.breadcrumbs = assembleBreadCrumbs();

    // do something for specific route
    if (route.$$route.action == 'item') {
      $scope.item = $scope.items[params.itemId];
      $rootScope.title = $scope.item.name;
    }
  });
}]);

braaam avatar Jul 29 '13 22:07 braaam

I have the same issue as the topic author has and created modified version of solution described above.

app.factory('skipReload', [
    '$route',
    '$rootScope',
    function ($route, $rootScope) {
        return function () {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
                un();
            });
        };
    }
]);

Usage:

app.controller('ThingCtrl', ['$scope', '$http', '$location', 'skipReload', function ($scope, $http, $location, skipReload) {
    ...
    $scope.submit = function () {
        ...
        $http.post('thing', thing).success(function (id) {
            skipReload();
            $location.path('/thing/' + id).replace();
        });
    };
}]);

Using permanent event listener that tests templateUrl to decide whether to allow route reload, could break routing to other views that uses same templateUrl. For example, I routed to /thing/new and the view shows link to last added thing /thing/5, I'll be unable to navigate to thing 5 and to any other thing (even changing url in browser explicitly). Another problem with templateUrl testing is that templates could be specified by using template property (as string or function).

This hack allows to skip exactly one route reload and doesn't break routing.

sergey-buturlakin avatar Aug 12 '13 17:08 sergey-buturlakin

Also I've tried less verbose (for usage in controller) solution:

app.factory('location', [
    '$location',
    '$route',
    '$rootScope',
    function ($location, $route, $rootScope) {
        $location.skipReload = function () {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
                un();
            });
            return $location;
        };
        return $location;
    }
]);
app.controller('ThingCtrl', ['$scope', '$http', 'location', function ($scope, $http, location) {
    ...
    $scope.submit = function () {
        ...
        $http.post('thing', thing).success(function (id) {
            location.skipReload().path('/thing/' + id).replace();
        });
    };
}]);

Seems working fine.

sergey-buturlakin avatar Aug 12 '13 17:08 sergey-buturlakin

+1

dtelaroli avatar Aug 22 '13 20:08 dtelaroli

@sergey-buturlakin your $location.skipReload is just wonderful! I use it instead of DoNotReloadCurrentTemplate

tkrotoff avatar Aug 26 '13 19:08 tkrotoff

@sergey-buturlakin Your solution looks to be working for me. Thanks!

ryanwalls avatar Aug 30 '13 11:08 ryanwalls

after running skipReload() from https://github.com/angular/angular.js/issues/1699#issuecomment-22511464 it keeps reloading disabled it looks like un() should be called later

melnikaite-apoex avatar Sep 20 '13 17:09 melnikaite-apoex

It prevents any next reload, and should be called right before path change. When path change finished - "un" will be called.

sergey-buturlakin avatar Sep 20 '13 20:09 sergey-buturlakin

yes, but I wanted to skip reload only once, however proposed approach prevents any further reloading

melnikaite-apoex avatar Sep 23 '13 06:09 melnikaite-apoex

+1

raff77 avatar Oct 08 '13 16:10 raff77

+1

ghost avatar Oct 15 '13 13:10 ghost

+1

kdoran avatar Oct 18 '13 09:10 kdoran

PR https://github.com/angular/angular.js/pull/2398 only skips reload once. I don't know if it has merge conflicts with current master. If that's the case, just drop me a line and I'll fix it.

lrlopez avatar Oct 18 '13 10:10 lrlopez

I use the sergey's solution, while droping the useless (according to me) "un" variable and call.

This leads to:

  angular.module('services.locationChanger', [])
    .service('locationChanger', ['$location', '$route', '$rootScope', function ($location, $route, $rootScope) {

        this.skipReload = function () {
            var lastRoute = $route.current;
            $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
            });
            return this;
        };

        this.withoutRefresh = function (url, doesReplace) {
            if(doesReplace){
                $location.path(url).replace();
            }
            else {
                $location.path(url || '/');
            }
        };
    }]);

and any caller:

 locationChanger.skipReload().withoutRefresh("/", true);

mica16 avatar Oct 30 '13 02:10 mica16

+1

hsunami avatar Nov 21 '13 07:11 hsunami

+1

iamdenny avatar Nov 25 '13 06:11 iamdenny

+1

danrigsby avatar Nov 28 '13 02:11 danrigsby