Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS change url with $location

Tags:

I'm trying to change the URL with AngularJS, but not with a redirect, just change the URL after an event.

What I need is this:

www.myurl.com/inbox/1 to this www.myurl.com/inbox/25

In other words, just change the last Id.

I'm trying to do this:

$location.path('/inbox/'+id);

But what I'm getting is this:

www.myurl.com/inbox/1#/inbox/25

like image 341
Matheus Lima Avatar asked Jul 21 '14 19:07

Matheus Lima


People also ask

What is $location in AngularJS?

The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.

What is $window in AngularJS?

A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Which method of $location service is used to get the full URL of the current web page?

We will be using the $location. absURL() method to get the complete URL of the current page.

What is not recommended in AngularJS?

It is tempting to do too much work in the AngularJS controller. After all, the controller is where the view first has access to JavaScript via $scope functions. However, doing this will cause you to miss out on code sharing across the site and is not recommended by AngularJS documentation.


2 Answers

Angular enforces the idea of one page web app. Browsers don't take any actions on change of anything after '#' value. So the best practice is to add variable attributes in url after '#' value which will keep the base url and attribute look clean on browser's address bar as well as solve your problem. My advice is to keep username, page no. , or any specific attribute id after '#' value. In your case you should use something like above said

www.myUrl.com/#/inbox/25

or

www.myUrl.com/inbox/#/25

like image 162
binariedMe Avatar answered Sep 23 '22 22:09

binariedMe


usually angular URLs look like

www.myurl.com/#/inbox/1 

in which case

$location.url('/inbox/25'); 

should work for you

like image 39
Orane Avatar answered Sep 26 '22 22:09

Orane