2016-02-16 33 views
0

我發現很難使之適合於NG-重複遍歷它在視圖中重新定義的返回信息。在混合JSON巢角的forEach

我有一個索引兩種意見之一,我想年月涵蓋的國家(可能是1 +或無),然後每個國家內部,我想每一個事件的名稱(又可能是1+或沒有)。第二個觀點,我只是想通過事件的詳細信息,並通過傳遞以此來回報所有事件的詳細信息(姓名,MNAME,淨)事件索引號被調用這些細節。

數據:

{ 
months: [ 
    { 
    index: 201602, 
    year: "2016", 
    mon: "February", 
    country1: [ 
    { 
    index: 12345678, 
    l: [ 
     { 
     name: "Test1", 
     mname: "Test 1", 
     net: "February 10, 2016 11:39:00 UTC", 
     } 
    ] 
    }, 
    { 
    index: 23456789, 
    l: [ 
     { 
     name: "Test2", 
     mname: "Test 2", 
     net: "February 10, 2016 11:39:00 UTC", 
     } 
    ] 
    } 
    ], 
    country2: [ ] 
}, 
{ 
index: 201603, 
year: "2016", 
mon: "March", 
country1: [ 
{ 
    index: 546547657654, 
    l: [ 
     { 
     name: "Test1", 
     mname: "Test 1", 
     net: "March 10, 2016 11:39:00 UTC", 
     } 
    ] 
} 
], 
country2: [] 
}, 
{ 
index: 201604, 
year: "2016", 
mon: "April", 
country1: [ ], 
country2: [ 
{ 
    index: 78676756, 
    l: [ 
     { 
     name: "Test1", 
     mname: "Test 1", 
     net: "April10, 2016 11:39:00 UTC", 
     } 
    ] 
} 
] 
} 
] 
} 
+0

那麼,什麼是你的問題?是不是因爲某種原因或者什麼不能重複你的數組? –

+0

是的,我無法迭代陣列之上,我相信這是由於角度的限制,我需要與只是我將它傳遞給視圖之前需要的水平以某種方式重新定義陣列。 – medoix

回答

0

爲了NG重複的工作,你就必須提取一些其他陣列國數據(以某種方式轉變的初始數據)。

如果這些country字段具有一致的命名(例如每個字段上的'country'中綴),則可以將它們提取到它們自己的數組中,並使用ng-repeat對它進行迭代。

這裏是工作的解決方案。它假定該國陣所有有字「國家」在他們的名字:

function MyCtrl($scope) { 
    $scope.countriesData = prepData(sampleData); 

    function prepData(data) { 
     return data.months.map(function(yearMonth) { 
     var transformed = { yearMonth: yearMonth, countries: [] }; 
     for (var key in yearMonth) { 
      if (key.indexOf('country') != -1) { 
       transformed.countries.push(yearMonth[key]); 
      } 
     } 
     return transformed; 
     }); 
    } 
} 

var sampleData = { 
    months: { 
     //... 
    } 
} 

該解決方案利用您所提供的數據,並將其轉換成項目數組,像這樣的:{ yearMonth: yearMonth, countries: [] };

你「馬上就必須使它們像這樣:

<div ng-controller="MyCtrl"> 
<ul> 
    <li ng-repeat="entry in countriesData"> 
    ym-id: {{entry.yearMonth.index}} 
    <ul> 
     <li ng-repeat="country in entry.countries"> 
     <ul> 
      <li ng-repeat="event in country"> 
      event-id: {{event.index}} 
      </li> 
     </ul> 
     </li> 
    </ul> 
    </li> 
</ul> 
</div> 

您可以檢查這裏的小提琴:http://jsfiddle.net/tvy4jbvs/