我在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>
我们将不胜感激。及时回复。
答案 0 :(得分:2)
我看到的第一个问题是你的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>