12

How can I redirect or update the url? I cannot find any good documentation regarding this. Basically, what I want to do is to change the $routeParams dynamically and update the url with the new value.

My code looks like this:

if ($routeParams.time) {
        var url;
        $routeParams.time = encodeURIComponent(value);
        url = '/' + $routeParams.time + '/' + 'marketing/networks';
        $location.path(url);
    } else {
        $routeParams.time = encodeURIComponent(value);
        url =  '/' + $routeParams.time + $location.path();
        $location.path(url);
    }
carols10cents
  • 6,943
  • 7
  • 39
  • 56
Mythriel
  • 1,360
  • 5
  • 24
  • 45

3 Answers3

23

After reading the comments to my answer, I think maybe is not the right answer for this case. Please, before using this solution, read the comments and other answers. I'm not using Angular anymore so I don't feel qualified for answering.

I leave the original answer unmodified below:

You are changing the location properly but AngularJS it's not realizing that it changed. You can solve the problem using the method '$apply' of your scope like this:

$location.path( url );
$scope.$apply();

Or like this:

$scope.$apply( $location.path( url ) );

See $apply documentation here http://docs.angularjs.org/api/ng.$rootScope.Scope

Robert
  • 31,925
  • 8
  • 35
  • 33
  • 3
    You may experience a $apply already in progress error, if so see: http://stackoverflow.com/questions/18626039/apply-already-in-progress-error, it's easily fixable. – DrCord Aug 30 '14 at 22:56
  • 2
    You shouldn't ever need to call $apply unless you are interfacing from a non-Angular event. When using $apply consider using a "safe apply" approach: https://coderwall.com/p/ngisma This is NOT a case where you need to use apply! – MGot90 May 21 '15 at 21:06
3

You might want to try native browser object $window.location.href instead, according to http://docs.angularjs.org/guide/dev_guide.services.$location (in Caveats section).

Dimitrios Mistriotis
  • 2,626
  • 3
  • 28
  • 45
Tosh
  • 35,955
  • 11
  • 65
  • 55
2

you should use https://angular-ui.github.io/

ui-router

when using this you can do ...

state.go("route-name", {id:4});

much better than the built in routing service

The most voted answer is worrying!

danday74
  • 52,471
  • 49
  • 232
  • 283