AngularJS multiple templates in one page

13k views Asked by At

I have an index that serves a static header menu, and below that an ng-view that based on route, selects the right template. Like this for example:

<navbar>
    ...
</navbar>
<div ng-view>
</div>

Everything is good so far, when a specific route is hit, a template is loaded in that container with the associated controller.

Now, I have another page that is loaded inside ng-view, and it's fired when url "/dashboard" is hit. The problem is that the dashboard page, has a sidebar menu that also needs to contain some routing logic (more or less). When a link has been clicked from the sidebar menu, I have to load only the left hand side of the page (not the whole ng-view container).

I have identified two solutions:

1) Create a directive that stores that sidebar menu, and inject it in all of the pages that are handled by the sidebar menu ==> routing is still handled by ng-view.

2) Use ng-include and have some routing logic in the dashboard page like this:

 <a ng-click="templateType = 1">Template 1</a>
 <a ng-click="templateType = 2">Template 1</a>

 <div ng-if="templateType === 1" ng-include="template1" 
  ng-controller="Template1Controller"></div>
 <div ng-if="templateType === 2" ng-include="template2" 
  ng-controller="Template2Controller"></div>

Is there another approach? Or what is the best practice in handling both a sidebar that handles some routes, and a static menu that handles another routes, with the mention that the sidebar menu is only available on some of the routes.

I have provided a paint drawing, in the hope that I can explain my problem better.

enter image description here

2

There are 2 answers

4
Freezystem On

You can use UI-Router and give a shot at nested views. Here is a really good tutorial. I think what you're trying to achieve is mentioned at the end of the tutorial.

0
Hacker On

As all others have suggested you need to go for UI-router and nested views. It is great way to set up your page layout.

You can find the answer in Angular UI-Router How to create a "layout" state?