Angular.js linq.js 过滤器无法正常工作

Angular.js linq.js Where filter not working properly

我在 AngularJs 中使用 linq.js,我在很多地方都在使用它,现在它工作正常,但我在不同的地方使用它,它对我不起作用。不工作意味着我没有达到预期的结果,它总是显示 {}。如果我做错了什么,请看下面的代码。

var app = angular.module('testApp', ['angular.filter', 'angular-linq', 'ngSelect2']);
    app.controller('testController', function ($scope, $http, $timeout, $q, $linq){
    $scope.Vendors = 
    [
      {VendorId:"VND001", VendorName:"Pharma Plus Pharmacy", Address:"Bahawalpur"},
      {VendorId:"VND001", VendorName:"Pakistan Pharma", Address:"Bahawalpur"}
    ];
    $scope.InvoiceItems = 
    [
     {
        VendorId:"VND001", 
        ItemName:"Gold Set Jewellery", 
        ItemDesc:"Some Description", 
        Cost:280.50, 
        Quantity:50 
     },
     {
        VendorId:"VND001", 
        ItemName:"First Class HandWatch", 
        ItemDesc:"Some Description", 
        Cost:100.50, 
        Quantity:50 
     },
     {
        VendorId:"VND002", 
        ItemName:"Gold Set Jewellery", 
        ItemDesc:"Some Description", 
        Cost:280.50, 
        Quantity:50 
     },
     {
        VendorId:"VND002", 
        ItemName:"First Class HandWatch", 
        ItemDesc:"Some Description", 
        Cost:100.50, 
        Quantity:50 
     },
    ];
    $scope.totalAmount = function(vendorId){
       return $linq.Enumerable().From($scope.InvoiceItems).Where("x => x.VendorId =="+vendorId).Select(function(x){
          return (+x.Cost)*x.Quantity;
       }).Sum();
    }
  }
}

请往下看html

<div class="row" ng-app="testApp">
  <div class="col-xs-12" ng-controller="testController" ng-init="initializeDefault()">
    <div ng-repeat="v in Vendors">
        <div>{{ v.VendorId }}</div>
        <div>{{ v.VendorName }}</div>
        <div>{{ v.Address }}</div>
        <div>{{ totalAmount(v.VendorId) }}</div>
    </div>
  </div>
</div>

我们将不胜感激。

我看到的第一个问题是 where 子句中的谓词格式不正确。

x.VendorId 是一个字符串,您正试图将它与传入的 vendorId 进行比较。但是你生成的 lambda 是有效的:

x => x.VendorId ==VND001

这不会产生任何结果。

相反,您需要生成:

x => x.VendorId == 'VND001'

您的查询应该是(使用更紧凑的 lambda 语法):

$linq.Enumerable().From($scope.InvoiceItems)
    .Where("$.VendorId == '" + vendorId + "'")
    .Select("+$.Cost * $.Quantity")
    .Sum();

但是,如果您预先组合这些查询并将总和作为查询的一部分而不是单独的查询,那会更好。您必须加入两个数组。

$scope._vendors = ...;
$scope._invoiceItems = ...;
$scope.VendorQuery = function() {
    return $linq.Enumerable().From($scope._vendors)
        .GroupJoin($scope._invoiceItems, "$.VendorId", "$.VendorId",
            "{ Id: $.VendorId, Name: $.VendorName, Address: $.Address, "
            + "Total: $$.Sum('+$.Cost * $.Quantity') }")
        .ToArray();
}

然后绑定到您的视图:

<div ng-repeat="v in VendorQuery()">
    <div>{{ v.Id }}</div>
    <div>{{ v.Name }}</div>
    <div>{{ v.Address }}</div>
    <div>{{ v.Total }}</div>
</div>