javascript - Angularjs:如何 ng-repeat 具有也是数组的字段的对象数组?

标签 javascript arrays angularjs angularjs-ng-repeat

我有一个如下所示的数组:

0: {ID: null, 
 name: "test", 
 city: "Austin", 
 UserColors: [{color: "blue"},{hobby:"beach"} ... ]}
 }...

我正在尝试 ng-repeat 初始数组,但是一旦我尝试遍历列表,我什么也看不到,这是 html/angular

      <tr ng-repeat="c in vm.people">
                        <td>{{c.name}}</td>
                        <td>{{c.city}}</td>   

                        <td ng-repeat="uc in c.UserColors">
                            <td>{{uc.color}}</td>
                        </td>

                    </tr>

我不确定哪里出了问题,非常感谢您的帮助,在此先感谢您。

最佳答案

我将使用自定义过滤器处理该字段:

<td ng-repeat-start="(key, value) in c.UserColors  | reduce">
      <b>{{key}}</b>
</td>
<td ng-repeat-end>
      {{value}}
</td>

过滤器:

app.filter("reduce",function() {
  return function(items) {
    var x = items.map(o => Object.entries(o));
    var x2 = x.reduce(((a,x) => (a.concat(x))), []);
    var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
    return x3;
  }
})

The DEMO

angular.module("app",[])
.controller("ctrl",function(){
  var vm = this;
  vm.people = {
    0: {ID: null, 
        name: "test", 
        city: "Austin", 
         UserColors: [{color: "blue"},{hobby:"beach"}]
      },
    1: {ID: null, 
        name: "best", 
        city: "Boston", 
         UserColors: [{colorx: "red"},{shirt:"black"}]
      },
    2: {ID: null, 
        name: "rest", 
        city: "Paris", 
         UserColors: [{colory: "yel"},{fruit:"peach"}]
      },
  }
})
.filter("reduce",function() {
  return function(items) {
    var x = items.map(o => Object.entries(o));
    var x2 = x.reduce(((a,x) => (a.concat(x))), []);
    var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
    return x3;//items;
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl as vm">
    <h3>Table</h3>
    <table>
      <tr ng-repeat="c in vm.people">
        <td>{{c.name}}</td>
        <td>{{c.city}}</td>   

        <td ng-repeat-start="(key, value) in c.UserColors  | reduce">
              <b>{{key}}</b>
        </td>
        <td ng-repeat-end>
              {{value}}
        </td>
        
      </tr>
    </table>
  </body>

关于javascript - Angularjs:如何 ng-repeat 具有也是数组的字段的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50707766/

相关文章:

css - 我可以将范围变量从 AngularJS 传递到 LESS

php - HTML 获取 URL 参数

javascript - 有没有更有效的方法在 Canvas 中创建网格?

python - 如何从 xlsx 文件中读取并将特定列值存储到 python 中的数组中?

javascript - ng-repeat 隐藏重复项

arrays - 搜索数组中连续元素的索引

javascript - Angular 中有主 Controller 好吗?

javascript - 使用 Javascript 或 Ajax 发送电子邮件

javascript - 使用 Typescript 在 Angular2 中导出对象文字

javascript - 在 angularjs 中显示索引表