我正在尝试在列表中显示项目的详细信息。这应该通过延迟加载模板(详细信息为 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的完整示例
有没有办法改进我的解决方案,或者我缺少什么来加载外部模板?预先感谢!