angularjs - 如何从指令中的templateCache延迟加载模板

时间:2013-08-12 10:46:09

标签: templates angularjs lazy-loading directive

我正在尝试显示列表中项目的详细信息。这应该通过延迟加载模板(详细信息的DOM)来完成,因为模板非常大,我在列表中有很多项,所以使用ng-include的ng-show不起作用,因为它被编译成DOM并且表现非常糟糕。

经过实验,我找到了一个解决方案,只使用内联模板。我正在使用单击处理程序将带有detail-view指令的HTML呈现给DOM。

HTML

<div ng-controller="Ctrl">
    {{item.name}} <button show-on-click item="item">Show Details</button>  

    <div class="detailView"></div>

    <div ng-include="'include.html'"></div>
</div>

<!-- detailView Template -->
<script type="text/ng-template" id="detailView.html">
    <p>With external template: <span>{{details.description}}</span></p>
</script>

显示点击指令

myApp.directive("showOnClick", ['$compile', '$parse', function($compile, $parse) {

  return {
    restrict: 'A',
    scope: {
      item: "=item"
    },
    link: function (scope, element, attrs) {
        // Bind the click handler
        element.bind('click', function() {
            // Parse the item
            var item = $parse(attrs.item)(scope);

            // Find the element to include the details
            var next = $(element).next('div.detailView');

            // Include and Compile new html with directiv
            next.replaceWith($compile('<detail-view details="item"></detail-view>')(scope));

        });
     }
   };
}]); 

详情视图指令:

myApp.directive("detailView", ['$parse', '$templateCache', '$http', function($parse, $templateCache, $http) {    
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'detailView.html', // this is not working
    // template: "<div>With template in directive: <span>{{details.description}}</span></div>", // uncomment this line to make it work
    link: function (scope, element, attrs) {
        var item = $parse(attrs.details)(scope);
        scope.$apply(function() {
          scope.details = item.details;
        });
    }        
  };
}]); 

以下是完整的示例 Plunker

有没有办法改进我的解决方案,或者我缺少加载外部模板的内容? 先谢谢!

2 个答案:

答案 0 :(得分:1)

您还可以在Angular 1.1.5版中查看ng-if指令。 ng-if只会在条件为真时呈现html。所以这就变成了

<div ng-controller="Ctrl">
    {{item.name}} <button ng-if="showDetails" item="item" ng-click='showDetails=true'>Show Details</button>  

    <div class="detailView"></div>

    <div ng-include="'include.html'"></div>
</div>

答案 1 :(得分:0)

只需使用 ng-include

<div ng-controller="Ctrl" ng-init="detailsViewTemplateSource='';">
    {{item.name}} 
    <button ng-click="detailsViewTemplateSource = 'detailView.html'">
        Show Details
    </button>       
    <div ng-include="detailsViewTemplateSource"></div>
</div>

<!-- detailView Template -->
<script type="text/ng-template" id="detailView.html">
    <p>With external template: <span>{{details.description}}</span></p>
</script>