Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


All of these methods are jQuery-style getters. In other words, they can be used to
both get and set the value of a given URL's component. For example, to read the URL
fragment value you would use: $location.hash(), while setting the value would
require an argument to be supplied to the same function: $location.hash('top').


The $location service offers other methods (not listed in the previous table) to
access any part of a URL: the protocol (protocol()), the host (host()), the port
(port()), and the absolute URL (absUrl()). The methods are getters only. They
can't be used to mutate URLs.


Hashes, navigation within a page, and $anchorScroll


The side effect of using hashbang URLs is that the part of the URL after the # sign,
normally used to navigate within a loaded document, is "taken" to represent the
URL part interesting from a single-page web application point of view. Still, there
are cases where we need to scroll to a specified place in a document loaded into the
browser. The trouble is that, in hashbang mode, URLs would contain two # signs,
for example:


http://myhost.com/myapp#/admin/users/list?active=true#bottom


Browsers have no way of knowing that the second hash (#bottom) should be used
to navigate within a document, and we need a little bit of help from AngularJS here.
This is where the $anchorScroll service comes into play.


By default the $anchorScroll service will monitor URL fragments. Upon detecting a
hash that should be used to navigate within a document, it will scroll to the specified
position. This process will work correctly in both the HTML5 mode (where only one
hash is present in a URL) as well as in hashbang mode (where two hashes can make
it into a URL). In short, the $anchorScroll service does the job which is normally
performed by the browser, but taking the hashbang mode into account.


If we want to have more fine-grained control over the scrolling behavior of
the $anchorScroll service you can opt out from its automatic URL fragment
monitoring. To do so, you need to call the disableAutoScrolling() method
on the $anchorScrollProvider service in a configuration block of a module
as follows:


angular.module('myModule', [])
.config(function ($anchorScrollProvider) {
$anchorScrollProvider.disableAutoScrolling();
});
Free download pdf