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

标签 javascript angularjs angular

我想请求 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/

相关文章:

javascript - 如何使用 angularJs 打开本地目录?

css - 左 Angular 动画不起作用

javascript - 通过 Javascript 将属性添加到现有 div 标签

javascript - 如何在 AngularJS 中应用数组中的 CSS 代码?

javascript - angularjs http post 与 Angular 和 GAE

javascript - 无法将数据从应用程序组件传递到函数

javascript - 如何刷新 Angular 组件

javascript - NPM/错误 : EACCES: permission denied, 扫描目录

javascript - 创建一个 X 数量为一个字符的二维数组

angularjs - 非单页网络应用程序需要 requirejs 和 angularjs 吗?