How to build a full dynamic template in Angular?

2019-09-10 05:37发布

问题:

I want to ask the community of angular to help me to find the best way to solve this problem :

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" }
        ]
   }

and data like that :

 {
        "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.

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: Bonus, same question for angular 2 (even I actually need it in angular 1).

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.

回答1:

Yes, you should create directive with field config like this:

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

and render it like

<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>

and wrap it inside directive

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

directive:

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