michael_knight
michael_knight

Reputation: 4941

AngularJs $location.path with full url

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

Upvotes: 28

Views: 66417

Answers (3)

Robert Balicki
Robert Balicki

Reputation: 1633

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.

Upvotes: 22

arjabbar
arjabbar

Reputation: 6404

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.

Upvotes: 6

Xspirits
Xspirits

Reputation: 217

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.

Upvotes: 11

Related Questions