繁体   English   中英

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

[英]Dynamically load templates (partials) in Angular.js

我正在尝试根据参数将模板加载到 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>

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

我能以某种方式做到这一点吗? 我正在考虑使用 ng-switch: https : //jsfiddle.net/rsvmar2n/6/

但我确信有一种更有角度的方法来做到这一点。

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

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

为此创建指令,例如:

app.directive('myDirective', function(){
  return {
    restrict: 'E',
    scope: {item: '=item'},
    templateUrl: function(element, attrs){
      if (!attrs.type) return 'default.html';
      return attrs.type + '.html';
    }
  } 
});

然后您可以创建不同的模板,如 type1.html、type2.html...

在控制器中,您只需执行以下操作:

<my-directive ng-repeat="item in items" item="item", type="item.type">

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

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

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

和你的 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>

使用 ng-include 可以让您动态分配源 - 因此在您的父模板中您可以拥有

<div ng-include src="templateName"></div>

其中 templateName 是控制器中的变量名称

$scope.templateName = 'path/to/my/template.html';

并在摘要中更改此值应为您动态更新内容

根据条件,您可以加载单个或多个模板,如下所示。

ng-switch

ng-if="item.type=='type2'||item.type=='type3'"

LoadMultipleTemplate根据您的选择加载多个模板。

LoadSingleTemplate加载单个模板。

编辑

使用ng-include ,您可以通过这种方式加载动态视图。

在这个例子中,我没有设置任何条件。 但是在 ng-repeat 中你可以放另一个 ng-repeat 并且基于内部的 ng-repeat 你可以做这些事情。 但是对于内部 ng-repeat,您必须根据 json 对象进行制作。

加载视图

<div  ng-repeat="item in example.items" class="someClass" >

         <ng-include src="item.type + '.html'">{{item.type}}</ng-include>

</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM