28

I want to route the user to an url if he clicks ok in a modal. In my controller i receive urls like

var newUrl = http://localhost:3000/#/dashboard

var newUrl = http://localhost:3000/#/users

as variable.

If i then use

$location.path(newUrl);

it does not work. I also tried

$location.url(newUrl);

but my URL gets encoded like this.

http://localhost:3000/#/#%2Fdashboard

Is there a way to get only the path of the url?

Edit

this code is part of a service. A user make some inputs in a form and clicks on another link for example in the menu. Then a popup appears where he is asked to skip his form changes. If he clicks yes i get the requested url. This is from my development environment on the server of course it will be another url. So i can not just use

$location.path("/users")

for example

4
  • Simply do: $location.path('/users') or newUrl = '/users' Commented Nov 30, 2013 at 17:09
  • 2
    yes this works but i receive a full url as a parameter. Commented Nov 30, 2013 at 17:19
  • 1
    I reported this issue: github.com/angular/angular.js/issues/8617 Commented Aug 14, 2014 at 21:54
  • 1
    stackoverflow.com/questions/21073815/… suggests that you use $window.location.href = newUrl Commented Jul 15, 2015 at 21:50

3 Answers 3

22

I ran into this same problem when having Angular preventDefault $locationChangeStart events, force a save, and only redirect upon success. I define the following function in the body of the controller:

var baseLen = $location.absUrl().length - $location.url().length;
function getPath(fullUrl) { 
    return fullUrl.substring(baseLen);
}

It doesn't seem like a clean solution, but as a work around, it does the job. A RegEx might work better for you, if you don't know that your URLs are pointing to the same site.

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

Comments

11

You can use $location.absUrl().

See the official documentation: enter link description here

This method is getter only.

Return full url representation with all segments encoded according to rules specified in RFC 3986.

1 Comment

As you say, absUrl is a getter and not a setter, so how does this answer the question?!
6

May I offer a different solution:

    $scope.$on('$locationChangeStart', function(e) {
      if (meetsTheRequirementsToLeave()) {
        return;
      }
      var newPath = $location.path();
      e.preventDefault();
      checkIfUserWantsToLeave().then(function() {
        $location.path(newPath);
      });
    });

Within this event $location.path() returns the new path.

1 Comment

This is by far the cleanest solution +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.