Jonathan de M.
Jonathan de M.

Reputation: 9828

Change hash without reloading controller in AngularJS

I'm working on a currency converter, and I have url like #/currency/50/USD/to/EUR, where 50, USD and EUR are parameters. Now I have a switch function which swaps the currencies and keep the value to convert, I'd like to change the URL as well to something like #/currency/50/EUR/to/USD without reloading the controller, just change the hash. I have an idea on how to do with pure js, but is there any solution in angular way?

Upvotes: 4

Views: 13506

Answers (2)

Jonathan de M.
Jonathan de M.

Reputation: 9828

Ok following callmekatootie solution here's my result, I had to add a condition to be able to go out of my controller when required

controller('CurrencyConvertCtrl', function ($scope, $route){
    var lastRoute = $route.current;
    $scope.$on('$locationChangeSuccess', function(event) {
        if($route.current.$$route.controller === 'CurrencyConvertCtrl'){ 
        // Will not load only if my view use the same controller
            $route.current = lastRoute;
        }
    });
}

Upvotes: 7

callmekatootie
callmekatootie

Reputation: 11238

Check this answer out. It sounds just like what you need.

Basically, you seem to have two choices:

  1. Listen for $locationChangeSuccess event.
  2. In your $routeProvider definition, while defining the routes and the corresponding templated to load, specify the option reloadOnSearch = false.

Upvotes: 13

Related Questions