12

Im making an 'interactive menu' that moves along with user clicks. Im wondering if there is a way to include html templates in ng-switch, since all the logic is different in each 'switch' - it will result in huge html files.

<div class="content" ng-switch on="selection">
 <div ng-switch-when="1" >
   <h1>1</h1>
 </div>
 <div ng-switch-when="2">
   <h1>2</h1>       
 </div>
</div>
Nitsan Baleli
  • 5,393
  • 3
  • 30
  • 52

3 Answers3

19

Use ngInclude:

<div class="content" ng-switch on="selection">
    <div ng-switch-when="1" >
        <ng-include src="'template1.html'"></ng-include>
    </div>
    <div ng-switch-when="2">
        <ng-include src="'template2.html'"></ng-include>
    </div>
</div>

Note: Dont forget to use single quotes wrapped inside the double quotes if you are hard-coding the path.

AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • +1 just for pointing out the crucial point that one has to use single quotes as well, along with double quotes. If not used, the templates wont show up. – Devner Jan 24 '16 at 20:07
11

You should be able to do it with ng-include directive :

<div class="content" ng-switch on="selection">
    <ng-switch-when="1" ng-include="//TEMPLATE PATH">
    <ng-switch-when="2" ng-include="//TEMPLATE 2 PATH">
</div> 
Jérémy Dutheil
  • 6,099
  • 7
  • 37
  • 52
  • This is the better answer as it uses less markup (ng-include and switch on the same element) – CarbonDry Jul 18 '14 at 09:08
  • Sorry, my mistake looks like there are problems: https://github.com/angular/angular.js/issues/4731 – CarbonDry Jul 18 '14 at 10:02
  • 4
    As of Angular 1.2, you can't use ng-include inside ng-switch. If you want less markup than @CodeHater's answer, use
    – antoine Apr 25 '15 at 18:04
  • Can this be done by tweaking the Directive itself so that templateUrl only loads on switch – ericjam Sep 17 '15 at 18:45
  • I get an error using this method `Error: [$compile:multidir] Multiple directives [ngSwitchWhen, ngInclude] asking for transclusion on:
    `
    – ilyo Jan 20 '16 at 15:56
1
   **I used ng-Include this way.**

    <!-- Main content -->
    <div class="row">

      <!-- right col -->
      <section class="col-lg-12">
        <ul class="nav nav-tabs responsive ui-tabbed" id="myTab">
          <li class="active">
            <a  data-ng-click=' main.active.tab = "tab-1" '>Tab 1</a>
          </li>

    </ul>
    <!-- end responsive tabs -->

    <div class="tab-content ui-tabbed-contents responsive">
    <div data-ng-switch = " main.active.tab ">
      <div data-ng-switch-when='tab-1' >
        <ng-include src="'tab-one.html'" ></ng-include>
      </div>

    </div>

    </div>


    </div>
    <!-- end main tabs container -->
    </section>
Mateen Kadwaikar
  • 403
  • 4
  • 17