AngularJS - 获取过滤数据的长度

时间:2016-06-11 04:15:37

标签: angularjs angular-filters

我正在尝试获取过滤数据的长度,而是获得实际数据的长度,我已经过滤了仅具有属性placed的数据。 my plunk demo

我得到的结果

Total 3 Notifications

2 quantities of V 4 Vanilla should be prepared

3 quantities of Power cut should be prepared

结果我期待

Total 2 Notifications

2 quantities of V 4 Vanilla should be prepared

3 quantities of Power cut should be prepared

HTML

<p class="orderCounter">Total {{getOrderFoods(reduce).length }} Notifications</p>
<div ng-repeat="(key,data) in getOrderFoods() | filter: {confirm: 'placed'} | groupBy:'name'">
  <p><span>{{reduce(data)}}</span> quantities of <span>{{key}}</span> should be prepared </p>
</div>

控制器

$scope.getOrderFoods = function() {
var orderfood = [];

$scope.reduce= function(data){
   return data.reduce(function(previousValue,
   currentValue, currentIndex, array) {
  return previousValue + parseInt(currentValue.qty);
}, 0);
}

angular.forEach($scope.orders, function(order) {
  angular.forEach(order.orderfood, function(orderfoo) {
    if (orderfood.indexOf(orderfoo) == -1) {
      orderfood.push(orderfoo);
    }
  })
});
return orderfood;
}

JSON

$scope.orders = [{
"_id": "56e3bff0e9932ca6425e6f65",
"orderfood": [
  {
  "qty": "2",
  "confirm": "placed",
  "name": "V 4 Vanilla"
  }
],
"name": "Rohit",
"created": "2016-03-12T07:06:24.424Z"
},
{
"_id": "56e3bd5bc3791b973c048804",
"user": null,
"__v": 10,
"orderfood": [
  {
  "qty": "1",
  "confirm": "cancelled",
  "name": "V 4 Vanilla"
  },
  {
  "qty": "3",
  "confirm": "placed",
  "name": "Power cut"
  }
],
"name": "Rohit",
"created": "2016-03-12T06:55:23.244Z"
}];

my plunk demo

2 个答案:

答案 0 :(得分:1)

添加directive以查找已过滤数据的长度

<强>指令

app.filter('numKeys', function() {
    return function(json) {
        var keys = Object.keys(json)
        return keys.length;
    }
});

<强> HTML

<body ng-controller="MainCtrl">
    <p class="orderCounter">Total {{filtered | numKeys}} Notifications</p>
    <div ng-repeat="(key,data) in filtered =(getOrderFoods() | filter: {confirm: 'placed'} | groupBy:'name')">
        <p><span>{{reduce(data)}}</span> quantities of <span>{{key}}</span> should be prepared </p>
    </div>
</body>

<强> Plunker Demo

如果您有任何疑问,请告诉我。谢谢

答案 1 :(得分:0)

您可以将其设置为获得已过滤数组的长度。

ng-repeat="item in $data| filter:f as results"

现在您可以使用results检查其长度或与此类似的其他div。

ng-if="results.length === 0"