Chapter 6
- Lets us to programmatically manipulate different parts of the current URL
and have those changes reflected in the browser's address bar - Allows us to easily observe changes in different components of the current
URL and take actions in response to those changes - Intercepts the users' interactions with links on a page (such as clicking on the
tags) to reflect those interactions in the browser's history
Understanding the $location service API and URLs
Before we see practical examples of using the $location service, we need to get
familiar with its API. Since the $location service works with URLs, the easiest way to
get started is to see how the different components of a URL map to the API methods.
Let's consider a URL that points to a list of users. To make the example more
complex, we will use a URL that has all the possible components: a path, a query
string, and a fragment. The essential part of the URL could look as follows:
/admin/users/list?active=true#bottom
We could decipher this URL as: in the administration section, list all users that are
active and scroll to the bottom of the retrieved list. This is the only part of a URL that
is interesting from the point of view of our application, but in reality a URL is the
"whole package", with a protocol, host, and so on. This URL in its full form, will be
represented differently, depending on the mode (hashbang or HTML5) used. In the
following URL, we can see examples of the same URL represented in both modes. In
HTML5 it would look as follows:
http://myhost.com/myapp/admin/users/list?active=true#bottom
In hashbang mode it would take its longer, uglier form, which is as follows:
http://myhost.com/myapp#/admin/users/list?active=true#bottom
Regardless of the mode used, the $location service API will mask the differences
and offer a consistent API. The following table shows a subset of the methods
available on the API:
Method Given the above example, would return
$location.url() /admin/users/list?active=true#bottom
$location.path() /admin/users/list
$location.search() {active: true}
$location.hash() Bottom