2

我有以下對象,並希望創建一個過濾器按ParentCategoryID分組。AngularJs集團通過數據和顯示使用過濾器

[ 
{id : 116, Desciption : 'Item1', ParentID : 1, parent : 'Parent1'}, 
{id : 117, Desciption : 'Item2', ParentID : 2, parent : 'Parent2'}, 
{id : 118, Desciption : 'Item3', ParentID : 2, parent : 'Parent2'}, 
{id : 119, Desciption : 'Item4', ParentID : 1, parent : 'Parent1'} 
] 

所以結局會是

Parent1 
    Item1 
    Item4 
Parent2 
    Item2 
    Item3 

我的過濾器目前看起來是這樣的:

productDetailsApp.filter('groupBy', function() { 
    return function(list, group_by) {  
     var filtered = []; 
     var prev_item = null; 

     angular.forEach(list, function(item) { 
      if (prev_item !== null) { 
       if (prev_item[group_by] === item[group_by]) { 
        filtered.push(item); 
       } 
      } 

      prev_item = item; 
     }); 

     console.log(filtered); 
     return filtered; 
    }; 

}); 

和HTML:

<div data-ng-repeat="d in details | groupBy:'ParentID'"> 
      <h2 >{{d.parent}}</h2>   
      <li>{{d.Desciption}}</li> 
    </div> 

但這僅輸出輸出最後元素作爲fi的prev_item第一項始終爲空:

Parent1 
    Item4 
Parent2 
    Item3 

有人可以幫助我。

回答

5

從語義上講,重新安排數據會更有意義。變成這樣的東西。

[ 
    { 
     id: 1, 
     title: 'Parent 1', 
     items: [ 
      {id: 126, description: 'Item 1'}, 
      {....} 
     ] 
    } 
] 

然後使用嵌套重複。這個數據結構更準確地描述了實際情況,並會讓你的生活更輕鬆。如果重新安排數據不是一個選項,或者你不明白嵌套的ng-repeat讓我知道,我們可以找到一個替代方案。

+0

完美..謝謝! – Zaki