2016-02-25 73 views
2

我有一個數據結構是這樣的:訪問陣列內的陣列(NG-重複)

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

我想使用納克重複返回每個人對象的孩子,在一個連續的列表。

像這樣:

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

誰能幫助?

+0

也就是對象的數組,其中有一個數組,嘗試像它的思維和發佈你如何試圖訪問它的一些代碼。 –

+0

你不輸出父母嗎?你還試過了什麼? – charlietfl

回答

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>

+2

小錯誤...添加另一個父母與子女。減少拋出錯誤,因爲返回一個沒有'子女'屬性的數組' – charlietfl

+2

可以做'people.reduce(函數(a,b){0}返回a.concat(b.children) },[]);' – charlietfl

+1

@charlietfl謝謝你指出,非常有幫助,編輯包括你的sugegstion – paul