【问题标题】:Accessing an array within an array (ng-repeat)访问数组中的数组(ng-repeat)
【发布时间】:2016-02-25 21:04:00
【问题描述】:

我有这样的数据结构:

[
   {firstName: "John",
    secondName: "Smith",
    children: ["Fred", "Hannah"]
   },
   {firstName: "Daniel",
    secondName: "Evans",
    children: ["Maggie", "Eddie", "Maria"]
   }
]

我想使用 ng-repeat 在连续列表中返回每个人对象的 CHILDREN。

像这样:

<ul>    
    <li>Fred</li>
    <li>Hannah</li>
    <li>Maggie</li>
    <li>Eddie</li>
    <li>Maria</li>
</ul>

有人可以帮忙吗?

【问题讨论】:

  • 这是一个对象数组,其中有一个数组,试着这样想,然后贴一些代码来说明你是如何访问它的。
  • 你不输出父级吗?你也试过什么?

标签: arrays angularjs object ng-repeat


【解决方案1】:

您可以reduce 您的数据结构,然后再将其呈现给 ng-repeat。

var app = angular.module('myApp', [
  'my.controllers'
]);

var controllers = angular.module('my.controllers', []);

controllers.controller('MyController', function($scope) {
  var people = [{
    firstName: "John",
    secondName: "Smith",
    children: ["Fred", "Hannah"]
  }, {
    firstName: "Daniel",
    secondName: "Evans",
    children: ["Maggie", "Eddie", "Maria"]
  }, {
   firstName:"Childless",
   secondName: "Parent"
  },
  { 
   firstName:"Jeff",
   secondName: "Pasty",
   children: ["Mike"]
  }];

  $scope.allChildren = people.reduce(function(a, b) { return a.concat(b.children) },[]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController">
    <div ng-repeat='child in allChildren'>{{ child }}</div>
  </div>
</div>

【讨论】:

  • 小错误...添加另一个有孩子的父母。 reduce 抛出错误,因为返回的数组没有children 属性
  • 可以people.reduce(function(a, b) { return a.concat(b.children) },[]);
  • @charlietfl 感谢您指出这一点,非常有帮助,已编辑以包含您的建议
  • 就是这样!不敢相信我没有想到将它存储在一个新变量中。很好的建议 - 感谢两者。
猜你喜欢
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2017-08-18
  • 1970-01-01
  • 2015-03-16
相关资源
最近更新 更多