AngularJS: Change hash and route without completely reloading controller AngularJS: Change hash and route without completely reloading controller angularjs angularjs

AngularJS: Change hash and route without completely reloading controller


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...


Brief Answer:

You can use the $location.search() method as you mentioned. You should listen to the "$routeUpdate" event on scope instead of other route events. $route API.

Explanation:

  1. First of all (you already know), add reloadOnSearch: false to your $routeProvider:

    $routeProvider.when('/somewhere', {    controller: 'SomeCtrl',    reloadOnSearch: false})
  2. Change your anchor tag href or ng-href to href="#/somewhere?param=value" this will trigger $routeChangeSuccess event if the path part (/somewhere) is not the same as current location. Otherwise it will trigger $routeUpdate event.

  3. Listen event on scope:

    $scope.$on("$routeUpdate", function(event, route) {    // some code here});
  4. If you want to change search params in code, you can use $location.search() method. $location.search API.


If you set reloadOnSearch to false, you can set the ?a=b&c=d portion of the url without reload. You can't change the actual location prettily, though, without a reload.