I am using linq.js in AngularJs, I am using in many places and its working fine now I used in different place and it doesn't work for me. Not working means I am not achieving the desired result it always showing {}
. please take a look below code if I am doing something wrong.
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();
}
}
}
Please take a look below 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>
Prompt response will be appreciated.
The first problem I see is that your predicate in the where clause is malformed.
The x.VendorId
is a string and you're trying to compare it to the passed in vendorId
. But the lambda you generate is effectively:
x => x.VendorId ==VND001
which would yield no results.
Instead you need to generate:
x => x.VendorId == 'VND001'
Your query ought to be (using the more compact lambda syntax):
$linq.Enumerable().From($scope.InvoiceItems)
.Where("$.VendorId == '" + vendorId + "'")
.Select("+$.Cost * $.Quantity")
.Sum();
However, it would be better if you combined those queries up front and include the total sum as part of the query, rather than a separate one. You'll have to join the two arrays.
$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();
}
Then bind to your view:
<div ng-repeat="v in VendorQuery()">
<div>{{ v.Id }}</div>
<div>{{ v.Name }}</div>
<div>{{ v.Address }}</div>
<div>{{ v.Total }}</div>
</div>