gpt4 book ai didi

javascript - 如何在 Angular 中构建完整的动态模板?

转载 作者:行者123 更新时间:2023-11-28 18:23:14 25 4
gpt4 key购买 nike

我想请求 Angular 社区帮助我找到解决这个问题的最佳方法:

我有这样的 json 数据:

{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}

以及类似的数据:

 {
"id": "0001",
"gloss": "donut",
"test": "Cake",
"ppu": 0.55,
"batter":
[
{ "id": "1001", "name": "Regular" },
{ "id": "1002", "name": "Chocolate" },
{ "id": "1003", "name": "Blueberry" },
{ "id": "1004", "name": "Devil's Food" }
]

}

在每种情况下,我都希望数据位于一个简单的表中,但列中具有不同的字段。

例如,我想在第一个中获取:id,type,topping.type,在第二个中获取:id,gloss,ppu,topping.type,name

是否可以使用可以处理两种情况(以及其他情况?)的自定义模板或指令来解决此类问题,以避免执行多个繁重的相似模板?

如果您需要更精确,我可以为您提供更多详细信息。谢谢。

PS:额外的福利,对于 Angular 2 来说也是同样的问题(即使我实际上在 Angular 1 中需要它)。

编辑:好的,我们开始吧:我需要得到类似的东西:https://plnkr.co/edit/iBENCVpRdohwAtm4AA54但我完全不知道如何实现这一点,假设 data1.json 和 data2.json 仅在这里,数据来自网络服务。但我正在寻找此类问题的全局解决方案。

最佳答案

是的,您应该使用如下字段配置创建指令:

var config = [{
title: 'Column name',
renderer: function valueRenderer(item){ return item.id}
}];

渲染它就像

<table>
<thead>
<th ng-repeat="column in config" ng-bind="column.title">
</thead>
<tbody>
<tr ng-repeat="item in data">
<td ng-repeat="column in config" ng-bind="column.renderer(item)"></td>
</tr>
</tbody>
</table>

并将其包装在指令内

<my-dir config="ctrl.config" data="ctrl.data"></my-dir>

指令:

module.directive('myDir', function(){
return {
restrict: 'E',
scope: {
data: '=',
config: '='
},
template: '<table ....'
};
});

关于javascript - 如何在 Angular 中构建完整的动态模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596658/

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