3

リスト内のアイテムの詳細を表示しようとしています。テンプレートが非常に大きく、リストに多くのアイテムがあるため、これはテンプレートを遅延読み込みすることによって行う必要があります (詳細については DOM)。 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は、条件が true の場合にのみ 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 に答える