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