131

I'm having an issue with changing the URL of the page after a form has been submitted.

Here's the flow of my app:

  1. Routes are set, URL is recognized to some form page.
  2. Page loads, controller sets variables, directives are fired.
  3. A special form directive is fired which performs a special form submission using AJAX.
  4. After the AJAX is performed (Angular doesn't take care of the AJAX) then a callback is fired and the directive calls the $scope.onAfterSubmit function which sets the location.

The problem is that after setting the location the nothing happens. I've tried setting the location param to / as well... Nope. I've also tried not submitting the form. Nothing works.

I've tested to see if the code reaches the onAfterSubmit function (which it does).

My only thought is that somehow the scope of the function is changed (since its called from a directive), but then again how can it call onAfterSubmit if the scope changed?

Here's my code

var Ctrl = function($scope, $location, $http) {
  $http.get('/resources/' + $params.id + '/edit.json').success(function(data) {
    $scope.resource = data;
  });

  $scope.onAfterSubmit = function() {
    $location.path('/').replace();
  };
}
Ctrl.$inject = ['$scope','$location','$http'];

Can someone help me out please?

4
  • 1
    possible duplicate of Angular $location.path not working Commented Nov 6, 2014 at 1:53
  • Keep in mind that this was created a year before that one. Commented Nov 6, 2014 at 5:13
  • Right and with the benefit of an extra year, the other one has a more precisely correct accepted answer. Commented Nov 6, 2014 at 6:35
  • 1
    @JimG. this is not a duplicate, this question is 4 years ago, the one you link, is 2 years ago. Commented Aug 16, 2016 at 21:24

9 Answers 9

304
+50

I had a similar problem some days ago. In my case the problem was that I changed things with a 3rd party library (jQuery to be precise) and in this case even though calling functions and setting variable works Angular doesn't always recognize that there are changes thus it never digests.

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Try to use $scope.$apply() right after you have changed the location and called replace() to let Angular know that things have changed.

Sign up to request clarification or add additional context in comments.

14 Comments

To get a better idea of how $apply works with angular and how to work around it's issues, here's a link for that yearofmoo.com/2012/10/…
@Skeater You can simply inject the root scope and operate on it like so: factory('xyz', ['$rootScope', function($rootScope) {...}])
@Flek can you provide a code example to help make this answer more usefl? Obviously a lot of people are finding it to be correct and helfpul, but I am not seeing the situation.
can wrap your callback with $timeout and the scope will be properly applied
Like JasonS said, use $timeout(function() { //apply changes here }); This has two advantages: 1) You don't need access to $scope. 2) You don't have to worry about $apply alredy running. For The 2nd reason, using $timeout is often the preferred approach.
|
55

Instead of $location.path(...) to change or refresh the page, I used the service $window. In Angular this service is used as interface to the window object, and the window object contains a property location which enables you to handle operations related to the location or URL stuff.

For example, with window.location you can assign a new page, like this:

$window.location.assign('/');

Or refresh it, like this:

$window.location.reload();

It worked for me. It's a little bit different from you expect but works for the given goal.

2 Comments

me too, $location.path() does not redirect when url has params
This is the correct answer. See here
29

I had this same problem, but my call to $location was ALREADY within a digest. Calling $apply() just gave a $digest already in process error.

This trick worked (and be sure to inject $location into your controller):

$timeout(function(){ 
   $location...
},1);

Though no idea why this was necessary...

7 Comments

Nooo this is a bad idea. Just check for phase incase it's within a digest and then you can skip the apply. Angular will catch up with it and change the URL on its own: coderwall.com/p/ngisma
timeout seems like a dirty hack to me. If your href contains "#", the $location.path() doesnt work as expected. Just remove entirely href="#" on your a tag or just set to href="" and you wouldnt need to use $timeout
$$phase is a private variable that you should not attempt to access because it might change in a new angularjs version.
Using $timeout might be a hack, but using $$phase is an even bigger hack. Generally, do not view or touch anything prefixed with $$.
After about 10 hours of random things breaking... this solution worked for me!
|
6

I had to embed my $location.path() statement like this because my digest was still running:

       function routeMe(data) {                
            var waitForRender = function () {
                if ($http.pendingRequests.length > 0) {
                    $timeout(waitForRender);
                } else {
                    $location.path(data);
                }
            };
            $timeout(waitForRender);
        }

1 Comment

for me the problem was we were using angular-block-ui and it was preventing the update of the address bar location. we decorated the $http request with a bool that our requestFilter picked up so that block-ui didn't trigger on that particular call, and then everything was fine.
2

In my case, the problem was the optional parameter indicator('?') missing in my template configuration.

For example:

.when('/abc/:id?', {
    templateUrl: 'views/abc.html',
    controller: 'abcControl'
})


$location.path('/abc');

Without the interrogation character the route obviously would not change suppressing the route parameter.

1 Comment

It's not template configuration but route configuration.
1

If any of you is using the Angular-ui / ui-router, use:$state.go('yourstate') instead of $location. It did the trick for me.

Comments

0

This wroks for me(in CoffeeScript)

 $location.path '/url/path'
 $scope.$apply() if (!$scope.$$phase)

Comments

0

In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.

Usually, when the $location doesn't work it means that something was not implemented the angular way.

In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.

The old code:

taskService.createTask(data).then(function(code){
            $location.path("task/" + code);
        }, function(error){});

Note: taskService.createTask returns a promise.

$q - the angular way to use promises:

let dataPromises = [taskService.createTask(data)];
        $q.all(dataPromises).then(function(response) {
                let code = response[0];
                $location.path("task/" + code);
            }, 
            function(error){});

Using $q to resolve the promise solved the redirection problem.

More on the $q service: https://docs.angularjs.org/api/ng/service/$q

Comments

-8
setTimeout(function() { $location.path("/abc"); },0);

it should solve your problem.

1 Comment

Running a non-setTimeout is a very bad idea. And, as @matsko said above, $timeout is not the best idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.