Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


Creating clickable links

AngularJS comes pre-bundled with the a directive, which prevents default actions
on links when the href attribute is omitted. This allows us to create clickable
elements using the a tag and the ng-click directive. For example, we can invoke
a function defined on a scope by clicking a DOM element rendered as the a tag
as follows:


<a ng-click='showFAQ()'>Frequently Asked Questions</a>

Having the a tags without a default navigation action is handy, as several CSS
frameworks use the a tags to render different types of visual elements, where a
navigation action doesn't make much sense. For example the Twitter's Bootstrap
CSS framework uses the a tags to render headers in tabs and accordion components.


Given the special behavior of the a tag without the href attribute, you might wonder
which method should be used to create actual navigation links. One might argue that
we could use the following equivalent methods:


<a href="/admin/users/list">List users</a>

Another method is as follows:


<a ng-click="listUsers()">List users</a>

where the listUsers method could be defined on a scope as follows:


$scope.listUsers = function() {
$location.path("/admin/users/list");
};

In practice, there are some subtle differences between the two approaches. To start
with links created using the href attribute are more user-friendly, since visitors can
right-click on such links and choose to open them in a separate tab (or window)
of a browser. In general, we should prefer navigation links created with the href
attribute, or even better with the AngularJS ng-href equivalent that makes it easy
to create dynamic URLs:


<a ng-href="/admin/users/{{user.$id()}}">Edit user</a>

Working with HTML5 and hashbang mode links consistently

The $location service in an AngularJS application can be configured with either
hashbang mode or HTML5 mode. This choice needs to be made upfront in a
configuration block, and links need to be created according to the chosen strategy.

Free download pdf