Developer
Developer

Reputation: 55

Load multiple views using angularjs

I have a scenario like this:

<a href="#">Link1</a>
<a href="#">Link2</a>

<div id="child1"></div>
<div id="child2"></div>

I'm using ngRoute (standard AngularJS router) in my app.


i.e: I expect a different set of views for different links. How can this be accomplished using AngularJS. I understand that Angular does provide routing, but whatever examples I see online is only for a single view.

I have kept this scenario very simple. In reality it is a lot more complicated so I will not be able to combine 2 views into 1 for each link.

Upvotes: 0

Views: 494

Answers (2)

JeanJacques
JeanJacques

Reputation: 1754

Another suggestion, you can use ui-router and multiple named views it's easy to use and really powerful.

You can create your different view container using ui-view like this

<a href="#" >Link1</a>

<a href="#" >Link2</a>

<div ui-view="child1"></div>
<div ui-view="child2"></div>

And in you app.config, you can set for every states which template you want to load for the different views :

.state('report', {      
    views: {        
      'child1': { ... templates and/or controllers ... },       
      'child2': {}      
    }

Upvotes: 0

Mistalis
Mistalis

Reputation: 18269

Here is a suggestion:

1) Make 4 templates (one per view):

  • viewA.html
  • viewB.html
  • viewC.html
  • viewD.html

2) Set 2 routes on your app (one per link):

$routeProvider.when('/page1', {
    templateUrl: 'page1.html',
    controller: 'Page1Ctrl'
}).when('/page2', {
    templateUrl: 'page2.html',
    controller: 'Page2Ctrl'
});

3) Include the views in page link1.html and link2.html

<!-- page1.html -->
<div id="child1" ng-include="'viewA.html'"></div>
<div id="child2" ng-include="'viewB.html'"></div>

<!-- page2.html -->
<div id="child1" ng-include="'viewC.html'"></div>
<div id="child2" ng-include="'viewD.html'"></div>

3) Set your <a> tags

<a href="#/page1">Link1</a>
<a href="#/page2">Link2</a>

Upvotes: 2

Related Questions