如何在ng-repeat angular中过滤后聚合对象属性

时间:2014-09-22 17:00:14

标签: angularjs

我正在使用Angular 1.2.16并过滤像这样的对象列表:

<li ng-repeat="item in filteredItems = (items | filter:query)">
  {{item.title}}
</li>

我可以说下面有“items”数组

var items = [ { title: "foo", priority: 1 },
              { title: "bar", priority: 2 },
              { title: "bla", priority: 1 } ];

在用“b”过滤后,angular将“filteredItems”设置为

filteredItems == [ { title: "bar", priority: 2 },
                   { title: "bla", priority: 1 } ];

我要做的是计算每种优先级类型的出现次数,后置过滤器并打印出来。例如。给定上述场景的输出将打印priority-1 = 2, priority-2 = 1,然后在应用过滤器“b”后变为priority-1 = 1, priority-2 = 1

我应该怎样做角度?

我尝试创建一个新控制器,然后使用$scope.$parent.filteredItems,但filteredItems片段不会动态更新。

这是一个plunkr http://plnkr.co/edit/uA5TgBVFVEd89dHSP0Yo

2 个答案:

答案 0 :(得分:2)

更简单,但仍不理想:

http://plnkr.co/edit/wkGKYQus2exkLycIu9XB?p=preview

HTML:

<body ng-controller="ParentCtrl">
  <input ng-model="query" type="text"/>

  <ul>
    <li ng-repeat="item in items | filter : query">
      <pre>{{item}}</pre></li>
  </ul>
  <h3>Summary of items</h3>
  <p >
    Priority-1: {{items | filter : query | sumFilter: '1'}}<br>
    Priority-2: {{items | filter : query | sumFilter: '2'}}
  </p>
</body>

JS:

app.filter('sumFilter', function() {
  return function(items, value) {
    var summary = 0; 
    for (var i in items) {
      if (items[i].priority == value) {
        summary++;
      }
    }
    return summary;
  }
});

答案 1 :(得分:0)

This post by Ben Nadel最接近于通过添加自定义指令来回答我的问题,该指令在ng-repeat完成后触发事件。但是,它比我想要的要复杂一点。

我的最后一种方法是向控制器添加一个自定义$ filter,当输入更改时会触发该过滤器,最后创建一个可以打印出来的摘要对象。可以找到here。{/ p>

HTML:      

    <input ng-model="query" type="text" ng-change="myFilter(query)" />

    <ul>
      <li ng-repeat="item in items">
        <pre>{{item}}</pre></li>
    </ul>

    <h3>Summary of items</h3>
    <p >
      Priority-1: {{summary.p1}}<br>
      Priority-2: {{summary.p2}}
    </p>

  </body>

App.js

var app = angular.module('app', []);

app.controller('ParentCtrl', ['$scope', '$filter',
  function($scope, $filter) {

    $scope.originalItems = [{
      title: "foo",
      priority: 1
    }, {
      title: "bar",
      priority: 2
    }, {
      title: "bla",
      priority: 1
    }];

    $scope.items = $scope.originalItems;

    var summarize = function(items) {
      var summary = {
        p1: 0,
        p2: 0
      };
      for (var i in items) {
        switch (items[i].priority) {
          case 1:
            summary.p1++;
            break;
          case 2:
            summary.p2++;
            break;
        }
      }
      return summary;
    };

    $scope.myFilter = function(query) {
      $scope.items = $filter('myFilter')($scope.originalItems, query);
      $scope.summary = summarize($scope.items);
    }

    $scope.summary = summarize($scope.items);

  }
]);

app.filter('myFilter', ['$filter',
  function($filter) {
    return function(items, query) {
      return $filter('filter')(items, query);
    };
  }
]);