Dynamically load templates (partials) in Angular.js


I’m trying to load a template into an Angular app depending on a parameter. It would be inside a ng-foreach:

<body ng-app="MyApp" ng-controller="ExampleController as example">
   <div  ng-repeat="item in example.items" class="someClass" ng-switch="item.type">
      <!-- load a different template (partial) depending on the value of item.type -->

Fiddle: https://jsfiddle.net/rsvmar2n/1/

Can I somehow do that? I was thinking about using ng-switch: https://jsfiddle.net/rsvmar2n/6/

But I’m sure there’s a more angular way to do it.

Edit: I would like NOT to do an http request for every partial I would load (and I think ngInclude does that.

Edit2: Ended using ng-include and cached templates. https://jsfiddle.net/rsvmar2n/24/


You can call a function which returns the id of the template in ng-include and use cached templates. The working example shows what you can do.

the function in your controller which handles the template looks like:

$scope.getTemplate = function(item) {
    case "type1":
        return 'testtype1.html';
        return 'testtype2.html';

and your html

<script type="text/ng-template" id="testtype1.html">
  <p>This is the template 1</p>

<script type="text/ng-template" id="testtype2.html">
  <p>This is the template 2</p>

<body ng-app="MyApp" ng-controller="ExampleController">
  <div ng-repeat="item in items" class="someClass">
    <!-- load a different template (partial) depending on the value of item.type -->
    <div ng-include="getTemplate(item)"></div>

Answered By – Raphael Müller

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published