2013-12-23 25 views
0

在Angularjs中,有沒有一種方法可以讓我的所有模板都保存在地圖中。並根據需要訪問它們。來自地圖的Angularjs模板

<li class="commentList" ng-repeat="c in m.c" 
    ng-include="'template1.html'"> 
    </li> 
ng-repeat="c in m.c"

基於c.type我想加載不同類型的模板。 因此我想保持地圖c.type到模板:

{'type1':'<script type="text/ng-template" id="template1.html"> <div class="col1">..T1.</div></script>', 
'type2':''<script type="text/ng-template" id="template2.html"> <div class="col3">..T2.</div></script>'} 
+0

你可以保持所有的模板中的地圖。你可以將任何字符串格式解析爲模板。另一種方法是使用$ templateCache.get('key')。或者你有編譯模板的問題? – Daiwei

回答

0

我不知道你的HTML代碼應該做的事情,但可能這可以幫助你:

angular.module('myModule', []) 
    .run(function ($templateCache) { 
     $templateCache.put(
      'tmpl1.html', angular.element('#tmpl1.html').html()); 
     $templateCache.put(
      'tmpl2.html', angular.element('#tmpl2.html').html()); 
    }); 

在你如果你不得不採用上面的代碼來縮放你的地圖。如果您想通過type1(關鍵字)註冊模板,很容易。但是,如果你想使用template1.html,你將不得不改變地圖的關鍵或用正則表達式提取id。

還有一個grunt插件可以生成一個包含所有模板的JS文件:grunt-html2js

0

嘗試這樣

存儲模板文件的名稱在數組

<li class="commentList" ng-repeat="c in m.c"> 
<load-templates item="c"></load-templates> 
</li> 

和JS

appname.directive('loadTemplates', function ($compile, $http) { 
    return { 
     restrict: 'E', 
     replace: true, 
     link: function ($scope, $element) { 
      $http.get('path to template/'+$scope.item+'.html').success(function (html) { 
       $element.html(html).show(); 
       $compile($element.contents())($scope); 
       // if you wish to do some other functions on the templates goes here 
      }); 
     }, 
     scope: { 
      item: '=' 
     } 
    } 
});