Mastering Web Application

(Rick Simeone) #1
Chapter 6

Structuring pages around routes

Before we dive into code samples, we should note that in a typical web application
there are "fixed parts" of a page (header, footer, and so on) as well as "moving parts",
which should change in response to the user's navigation actions. Taking this into
account, we should organize markup and controllers on our page in such a way that
fixed and moving parts are clearly separated. Building on the previously seen URL
examples, we could structure the application's HTML as follows:


<body ng-controller="NavigationCtrl">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li><a href="#/admin/users/list">List users</a></li>
<li><a href="#/admin/users/new">New user</a></li>
</ul>
</div>
</div>
<div class="container-fluid" ng-include="selectedRoute.templateUrl">
<!-- Route-dependent content goes here -->
</div>
</body>

The moving part in the preceding example is represented by a

tag with the
ng-include directive referencing a dynamic URL: selectedRoute.templateUrl.
But how does this expression gets changed based on URL changes?


Let's examine the JavaScript part, by having a closer look at NavigationCtrl. Firstly,
we can define our routes variable as follows:


.controller('NavigationCtrl', function ($scope, $location) {

var routes = {
'/admin/users/list': {templateUrl: 'tpls/users/list.html'},
'/admin/users/new': {templateUrl: 'tpls/users/new.html'},
'/admin/users/edit': {templateUrl: 'tpls/users/edit.html'}
};
var defaultRoute = routes['/admin/users/list'];
...
});

The routes object gives a basic structure to the application, it maps all possible
partial templates to their corresponding URLs. By glancing over these routes
definition, we can quickly see which screens make up our application and which
partials are used in each route.

Free download pdf