AngularJS: Change hash and route without completely reloading controller

doubledriscoll picture doubledriscoll · Aug 24, 2012 · Viewed 37.3k times · Source

I have a controller, with a route like this:

#/articles/1234

I want to change the route without completely reloading the controller, so I can keep the position of other stuff in the controller constant (lists that scroll)

I can think of a few ways to do this, but they're all pretty ugly. Is there a best practice for doing something like this? I tried experimenting with reloadOnSearch: false, but it doesn't seem to change anything.

Answer

Jens X Augustsson picture Jens X Augustsson · Jan 15, 2013

Had the very same challange,

Found a hack in another StackOverflow response that did the trick

Fairly clean solution - all I did was to add these lines to the controller that sets $location.path:

var lastRoute = $route.current;
$scope.$on('$locationChangeSuccess', function(event) {
    $route.current = lastRoute;
});

..and made sure $route in injected into the controller of course.

But still, feels like "DoNotFollowRoutesOnPathChange" is a missing feature in AngularJS.

/Jens

Update: Since listening to this event effectively kills further usage of $routeProvider configs, I had to limit this catch to current path only:

    var lastRoute = $route.current;
    if ($route.current.$route.templateUrl.indexOf('mycurrentpath') > 0) {
        $route.current = lastRoute;         
    }

Getting ugly...