How can I dynamically load multiple templates using AngularJS?

I am new to AngularJS, coming from the background of PHP, where I do all the template aggregation on the server. With PHP, I would take several templates, combine them together, and then send them to the client browser. AngularJS allows me to insert a template using ng-view . This is great, but it does not handle the case where the template I am inserting may include tags that are placeholders for other templates. For example, I might have the following as one of my templates:

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

In PHP, I would embed this template, and then replace the {content} 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 can this be done using AngularJS?

+8
angularjs
source share
2 answers

A direct 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 the controller that is associated with this template, you can dynamically define the templatePath variable:

 function MyCtrl($scope){ $scope.templatePath = // define this var dynamically here } 
+17
source share

Using ng-view to insert multiple templates is currently not supported natively in Angular.js. However, there are several options for emulating this functionality. See the answers to this SO question for several of these options, including the ui-router proposed by akonsu.

+3
source share

All Articles