簡體   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