2016-01-13 27 views
3

我想根據參數將模板加載到Angular應用中。這將是一個NG-的foreach內:在Angular.js中動態加載模板(部分)

<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-包括緩存模板https://jsfiddle.net/rsvmar2n/24/

+0

什麼'ngInclude'? – maurycy

+0

是的。我想到了這一點,但我不清楚它是如何工作的(Angular文檔的魔力)。我應該從我的服務器公開一些HTML,然後用ngInclude加載它們嗎?你可以帶一個代碼示例嗎?我不想爲每個部分加載一個http請求(我認爲ngInclude會這樣做)。 – Astaroth

+2

你可以在'$ templatecache'上使用'ng-include' – nada

回答

2

你可以調用一個函數,它返回ng-include中模板的id並使用緩存模板。工作example顯示你可以做什麼。

在您的控制器,它處理的模板函數看起來像:

$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> 
+0

這就是我所做的:https://jsfiddle.net/rsvmar2n/24/ – Astaroth

2

對於創建指令,是這樣的:

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"> 
+1

我結束了這樣的操作:https://jsfiddle.net/rsvmar2n/ 22/ – Astaroth

0

隨着NG-開關

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

LoadMultipleTemplate要根據您的選擇加載多個模板。

LoadSingleTemplate加載單個模板。

編輯

隨着NG-包括,這樣你可以加載動態視圖。

在這個例子中,我沒有提出任何條件。但在ng-repeat內,你可以放入另一個ng-repeat並基於內部ng-repeat,你可以做這些事情。但對於內部的重複,你將不得不根據JSON對象。

loadViews

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

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

</div> 
0

採用NG-包括可以讓你動態分配的來源 - 所以在你的父模板,你可以有

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

其中TEMPLATENAME是在控制器變量名

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

並在摘要中更改此值應dynamika lly爲你更新內容