Sir Robert
Sir Robert

Reputation: 4946

Angular: How can I use different templates for different views?

I've got an AngularJS site. The index.html used to look something like this:

...
<div class="layout stuff headers whatever">My awesome header layout</div>
<div class="container" ng-view=""></div>
<div class="layout stuff footers whatever">My tubular footer layout</div>
...

Generally, the site layout was defined in the layout stuff above and below the view.

Working with our designer, now I have three different basic page layouts. All the original views have their same (common) layout, but there are a half dozen new pages that each have one of two new layouts.

I guess I could move the header stuff for each layout into a partial and the footer stuff for each layout into a partial. Then I would have to do an ng-include in each view, like this:

<div ng-include src="'partials/layout1-header.html'"></div>
... view content here ...
<div ng-include src="'partials/layout1-footer.html'"></div>

O me miseram! That's ugly and makes me feel like I need a shower to DRY off.

Is there a better solution? Does angular have a way of dealing with this that I just haven't encountered yet?

Note: I'm not especially interested in using angular-ui-route... but I'm willing to be convinced.

Upvotes: 1

Views: 969

Answers (1)

Sir Robert
Sir Robert

Reputation: 4946

Ok, so it looks like the best approach is to use ui-router.

For what it's worth:

Assume the following page layout types:

  • info
  • dashboard
  • lookup

Further, let's assume that each of these layouts has different views, such as:

  • dashboard/account/overview
  • dashboard/account/settings
  • dashboard/reports
  • dashboard/reports/summary
  • ... and so on ...

First, create templates for each level of your site (assume there's no explicit template for the "account" portion of the path-- the overview, settings, report stuff, etc. all just gets loaded into the dashboard layout.

./partials/dashboard.html
./partials/dashboard/account/overview.html
./partials/dashboard/account/settings.html

You'll want to set up the ui-router like this:

$stateProvider
  .state("dashboard", {
    url: "/dashboard",
    templateUrl: "partials/dashboard.html"
  })
  .state("dashboard.account", {
    url: "/account", // notice this chains from "/dashboard" implicitly
    template: "<div ui-view></div>" // we don't need a file for this pass-through
  })
  .state("dashboard.account.overview", {
    url: "/overview",
    templateUrl: "partials/dashboard/account/overview",
    controller: "DashboardAccountOverviewCtrl"
  })

and so on. Controllers can be specified as you would expect (see dashboard.account.overview).

Doing this lets you specify which layouts should be used at the "dashboard" or "info", etc. level and use various "inner" templates for the other stuff (it's what ui-view means by "nested views").

HTH.

Upvotes: 1

Related Questions