在AngularJS中如何从过滤结果中获得总计?

时间:2015-08-31 15:07:09

标签: angularjs

我使用Angular和PHP来检索已过滤的发票清单。我想显示所有过滤结果的总和。

这是我的Controller文件:

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

myApp.controller('MyController', ['$scope', '$http', function($scope, $http) {
    $scope.min_date = 000000;
    $scope.max_date = 999999;

    $http.get('getinvoice.php').success(function(data) {
        $scope.invoices = data;
    });

    $scope.dateFilter = (function(invoice) {
        return (invoice.dateshort > $scope.min_date - 1 && invoice.dateshort < $scope.max_date + 1);
    });

    $scope.totalPrice = function() {
        var total = 0;
        for (count = 0; count < $scope.invoices.length; count++) {
            total += $scope.invoices[count].total;
        }
        return total;
    }
}]);

以下是HTML页面:

<section id="searchpage" ng-app="myApp" ng-controller='MyController' >
  <div class="search" >

    <label>Search: </label>
    <input id ='search' ng-model="query" placeholder="Search Invoices" autofocus>
    <label>Min Date:</label><input id='mindate' ng-model="min_date" />
    <label>Max Date:</label><input id='maxdate' ng-model="max_date" />

    <br><br>   
  </div>

  <table class="customerlist" ng-show="query" ng-init="tot=0.00">
    <tr>
      <th class='border'>Type</th>
      <th class='border'>Date</th>
      <th class='border'>Customer Name</th>
      <th class='border'>Vehichle</th>
      <th class='border'>Total</th>
    </tr>
    <tr  class="customerrow" ng-repeat="invoice in filtered = (invoices | filter: query | filter: dateFilter)">
      <td class='border'>{{invoice.type}}</td>
      <td class='border'>{{invoice.dateshort}}</td>
      <td class='border'>{{invoice.name}}</td>
      <td class='border'>{{invoice.vehicle}}</td>
      <td calss='total'>{{invoice.total |currency }}</td>
      <td class='border'><a class="button" href="invre.php?id={{invoice.id}}&type={{invoice.type}}">View Invoice</a></td>
    </tr>
  </table> 
  <p>{{filtered.length}} Results</p>
  <p id = 'tline'>Total: {{totalPrice()}}</p>
</section>

目前,这会从一切产生总数。但是,这有两个问题。首先,它返回所有总计的列表:

Total: 0108.77614.860.0056.990.000.000.0032.4286.4930.9530.95

其次,这包括所有结果,而不是过滤结果。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以在控制器中访问$scope.filtered。在total()$scope.invoices应更改为$scope.filtered

$scope.totalPrice = function() {
        var total = 0;
        for (count = 0; count < $scope.filtered.length; count++) {
            total += $scope.filtered[count].total;
        }
        return total;
    }

答案 1 :(得分:0)

根据您发布的结果,似乎总数是连接(不是添加),就好像每个invoice.total都是字符串而不是数字。

因此,对于您的第一个问题,我建议您仔细检查从$http.get返回的内容。也许需要在客户端代码中进行转换,或者(更好的是)在服务器端需要从PHP实体到JSON的正确转换。

对于你的第二个问题,@ Aasem Gautam是对的:你应该只对过滤的发票进行总计,而不是全部。此外,您可以更多地使用功能,而不是在阵列上循环,所以说:

$scope.totalPrice = function() {
  var initialValue = 0;

  var total = $scope.filtered.reduce(function (partial, invoice) {
    return partial + invoice.total;
  }, initialValue);

  return total;
};

请参阅MDN Array.reduce了解参考资料

免责声明:手动编辑,可能会出现一些语法错误。如有需要请询问。