Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically load multiple templates using AngularJS?

Tags:

angularjs

I'm new to AngularJS, coming from a PHP background where I do all the template aggregation on the server. With PHP I would grab several templates, mash them together, then send it to the clients browser. AngularJS allows me to insert a template using ng-view. This is great, but it doesn't handle the case where the template that I insert may include tags that are placeholders for other templates. For example, I may have the following as one of my templates:

<div class="some_class">
    <div class="another_class">
        {content}
    </div>
</div>

In PHP I would insert this template, then replace the contents of {content} with another template. In AngularJS I know how to insert the main template (using ng-view), but I'm not sure how to dynamically load my "partial template" into the {content} tag. How is this suppose to be done with AngularJS?

like image 794
Nancy Collier Avatar asked Jun 30 '13 03:06

Nancy Collier


2 Answers

A straightforward approach would be to use the ngInclude directive:

<div class="some_class">
  <div class="another_class">
    <ng-include src="templatePath"></ng-include>
  </div>
</div>

Then, in Controller that is associated with this template you can define the templatePath variable dynamically:

function MyCtrl($scope){
  $scope.templatePath = // define this var dynamically here
}
like image 155
Stewie Avatar answered Nov 16 '22 13:11

Stewie


Using ng-view to nest multiple templates is not currently supported natively in Angular.js. There are, however, multiple options to emulate that functionality. See the answers in this SO question for several of those options, including the ui-router suggested by akonsu.

like image 40
John Woodruff Avatar answered Nov 16 '22 12:11

John Woodruff