3

我正在尝试在列表中显示项目的详细信息。这应该通过延迟加载模板(详细信息为 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的完整示例

有没有办法改进我的解决方案,或者我缺少什么来加载外部模板?预先感谢!

4

2 回答 2

1

您还可以查看ng-ifAngular 版本 1.1.5 中的指令。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>
于 2013-08-12T10:58:10.293 回答
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>
于 2013-08-12T11:24:30.827 回答