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
Overview. The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
hash() Method: It is a read and writes method of $location service. It returns the current hash value of the current URL when called without parameters and when called with parameters it returns the$location object.
The $window service refers to the browser window object. It is globally available in JavaScript, so it causes testability problems. In AngularJS, it is not globally available. It includes various methods like alert box, prompt box, confirms box, etc.
By using $location service in angularjs we can get information like full url of current web page, part of url of web page, protocol of web page, host information of current url and port of current url.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With