Organizing Navigation
The history API is supported in most of the modern browsers. When it
comes to Internet Explorer, it is only built in starting from Version 10.
The earlier versions work only with hashbang URLs.
In short, using the history API, we can simulate visiting external resources without
actually making round trips to the server. We can do so by pushing full, nicely
formatted URLs on top of the browser's history stack using the new history.
pushState method. The history API also has a built-in mechanism to observe
changes in the history stack. We can listen to the window.onpopstate event and
change the application's state in response to this event.
By using the HTML5 history API, we can once again work with nice URLs (without
the # trick) in single-page web applications and enjoy good user experience by using
bookmarkable URLs, back and forward buttons working as expected, and so on. The
URLs from the previous example could be simply represented as follows:
- http://myhost.com/admin/users/list
- http://myhost.com/admin/users/new
- http://myhost.com/admin/users/[userId]
Those URLs look very much like "standard" URLs, pointing to real resources on a
server. This is good, since we want to have nicely looking URLs. But if one of these
URLs is entered into the browser's address bar, a user agent can't distinguish this
URL from any other URL and it will issue a request to the server.
For the HTML5 mode to work correctly in such situations, the server
needs to be configured properly, and cooperate by always returning
the application's landing page. We are going to cover server setup for
the HTML5 URLs mode later in this chapter.
Using the $location service
AngularJS provides an abstraction layer over URLs (and their behavior) in the
form of the $location service. This service masks the difference between the
hashbang and the HTML5 URL modes allowing us, application developers, to work
with a consistent API regardless of the browser and the mode being used. But the
$location service does more heavy lifting, by providing the following functions:
- Provides convenient, clean API to easily access different parts of the current
URL (protocol, host, port, path, query parameters, and so on)