【问题标题】:AngularJs Group By Data and Display Using FiltersAngularJs 按数据分组并使用过滤器显示
【发布时间】:2014-02-24 15:36:52
【问题描述】:

我有以下对象并想创建一个过滤器以按 ParentCategoryID 分组。

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

但是这个输出只输出最后一个元素作为 prev_item 第一项总是为空:

Parent1
  Item4
Parent2
  Item3

谁能帮帮我。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat angularjs-filter


    【解决方案1】:

    从语义上讲,重新排列数据会更有意义。变成这样。

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

    然后使用嵌套重复。这种数据结构更准确地描述了实际情况,将使您的生活更轻松。如果重新排列数据不是一种选择,或者您不了解嵌套的 ng-repeats,请告诉我,我们可以找到替代方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多