访问数组中的数组(ng-repeat)

时间:2016-02-25 21:04:00

标签: arrays angularjs object ng-repeat

我有这样的数据结构:

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

在将数据结构呈现给ng-repeat之前,您可以reduce数据结构。

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>