动态加载Angular.js中的模板(部分)

Ast*_*oth 5 javascript angularjs

我正在尝试根据参数将模板加载到Angular应用程序中.这将是一个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 -->
   </div>
</body>
Run Code Online (Sandbox Code Playgroud)

小提琴: https ://jsfiddle.net/rsvmar2n/1/

我可以以某种方式这样做吗?我在考虑使用ng-switch:https://jsfiddle.net/rsvmar2n/6/

但我确信有一种更有棱角的方式来做到这一点.

编辑:我不想为我要加载的每个部分做一个http请求(我认为ngInclude会这样做.

Edit2:使用ng-include缓存模板结束.https://jsfiddle.net/rsvmar2n/24/

Rap*_*ler 3

您可以调用一个返回 ng-include 中模板 id 的函数并使用缓存的模板。工作示例显示了您可以做什么。

控制器中处理模板的函数如下所示:

$scope.getTemplate = function(item) {
    switch(item.type)
  {
    case "type1":
        return 'testtype1.html';
    default:
        return 'testtype2.html';
  }
}
Run Code Online (Sandbox Code Playgroud)

和你的html

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

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

<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>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)