如何在Angular中构建完整的动态模板? [英] How to build a full dynamic template in Angular?
问题描述
我想问一下angular社区,以帮助我找到解决此问题的最佳方法:
I want to ask the community of angular to help me to find the best way to solve this problem :
我在json中有这样的数据:
I have data like this in 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" }
]
}
在每种情况下,我都希望数据位于一个简单的表中,但各列中的字段不同.
In each case I want the data to be in a simple table but with different fields in columns.
例如,我想在第一个中获取:id,type,topping.type,在第二个中获取:id,gloss,ppu,topping.type,名称
For example I want to get :id, type, topping.type in the first , and in the second : id, gloss, ppu, topping.type, name
是否有可能使用可以处理两种情况(以及其他两种情况)的自定义模板或指令来解决此类问题,从而避免制作多个笨拙的相似模板?
Is it possible to solve that kind of problem with a custom template or directive that can handle both case (and others?) to avoid doing multiple heavy similar templates?
如果您需要更高的精度,我可以为您提供更多详细信息.谢谢.
If you need more precision I can give you more details about it. Thanks.
PS:奖励,关于角度2的相同问题(即使我实际上在角度1中也需要它).
PS: Bonus, same question for angular 2 (even I actually need it in angular 1).
好的,我们开始:我需要得到类似的东西: https://plnkr.co/edit/iBENCVpRdohwAtm4AA54 但我完全不知道我该如何做到这一点,假设data1.json和data2.json仅在此处,则数据来自Web服务.但我正在寻找解决此类问题的全球解决方案.
Edit : Ok here we go : i need to get something like that : https://plnkr.co/edit/iBENCVpRdohwAtm4AA54 But i have absolutely no idea how can i acheive that, assuming that data1.json and data2.json are here only for example , data are comming from a webservice. but i'm searching the global solution to that kind of problems.
推荐答案
是的,您应该使用字段配置创建指令,如下所示:
Yes, you should create directive with field config like this:
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 ....'
};
});
这篇关于如何在Angular中构建完整的动态模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!