gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:44:08 25 4
gpt4 key购买 nike

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

经过试验,我想出了一个解决方案,只使用内联模板。我正在使用点击处理程序将带有详细 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));

});
}
};
}]);

详细 View 指令:

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

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

最佳答案

您还可以查看 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>

关于templates - angularjs - 如何在指令中从 templateCache 延迟加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18185043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com