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

时间:2016-09-20 14:22:28

标签: javascript angularjs 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:Bonus,同样的角度2的问题(即使我实际上需要角度1)。

编辑:好的,我们走了:我需要得到类似的东西:https://plnkr.co/edit/iBENCVpRdohwAtm4AA54但我完全不知道我怎么能实现这一点,假设data1.json和data2.json仅在这里举例,数据来自Web服务。但我正在寻找全球解决方案来解决这类问题。

1 个答案:

答案 0 :(得分:3)

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

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 ....'
   };
});