我收到像这样的JSON响应:
{
"productDesc": "Other posterior corneal dystrophies",
"ProductId": 1,
"productName": "Keylex",
"productPrice": 3529.24,
"productStatus": false,
"productStock": 23,
"productModifyDate": "2016-10-13T20:13:12",
"productUrl": "http://dummyimage.com/153x172.jpg/5fa2dd/ffffff",
"ReviewProducts": [
{
"ratingReview": 8.2,
"reviewDesc": "aaaaa",
"ReviewProductIdNumber": 1,
"User": {
"username": "hsullivan0",
"UserId": 1,
"name": "Heather",
"lastName": "Sullivan"
}
},
{
"ratingReview": 6.8,
"reviewDesc": "mattis pulvinar nulla pede ullamcorper augue a suscipit nulla elit ac nulla sed",
"ReviewProductIdNumber": 2,
"User": {
"username": "jcarrod",
"UserId": 878,
"name": "Jessica",
"lastName": "Carr"
}
}
]
}
我想要做的是计算平均评分从每个产品评论并显示它,现在我的HTML看起来像这样:
<div class="col-sm-4 col-lg-4 col-md-4" ng-repeat="x in product | limitTo:30">
<div class="thumbnail">
<img ng-src="{{x.productUrl}}" alt="">
<div class="caption">
<h4 class="pull-right">{{x.productPrice | currency}}</h4>
<h4>
<a href="#">{{x.productName}}</a>
</h4>
<p>{{x.productDesc}}.</p>
</div>
<div class="ratings" ng-repeat="review in x.ReviewProducts">
<p class="pull-right">{{review.ratingReview}}</p>
<p>
<span class="glyphicon glyphicon-star"></span>
</p>
</div>
</div>
</div>
不是BTW并非所有产品都有评论等级,所以万一没有显示任何内容
答案 0 :(得分:1)
创建如下功能
$scope.getAvg= function(ReviewProducts){
var total = 0;
for(var i = 0; i < ReviewProducts.length; i++)
{
total += ReviewProducts[i].ratingReview;
}
var avg = total / ReviewProducts.length;
return avg;
}
在div中调用此方法,如下所示
<div>{{getAvg(ReviewProducts)}}</div>
答案 1 :(得分:0)
您可以使用以下功能:
<div class="ratings">
<p class="pull-right">{{getAverage(x.ReviewProducts}}</p>
<p>
<span class="glyphicon glyphicon-star"></span>
</p>
</div>
和
$scope.getAverage = function(reviews){
var sum = 0;
var cpt = 0;
angular.forEach(reviews, function(review){
cpt++;
sum += review.ratingReview;
});
if(cpt === 0){
return 0;
}
return sum/cpt;
}
答案 2 :(得分:0)
您可以尝试使用以下过滤器。
.filter('ratingavg', function() {
return function(data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data, function(v, k) {
sum = sum + parseInt(v[key]);
});
return sum / data.length;
}
})
<div class="col-sm-4 col-lg-4 col-md-4" ng-repeat="x in product | limitTo:30">
<div class="thumbnail">
<img ng-src="{{x.productUrl}}" alt="">
<div class="caption">
<h4 class="pull-right">{{x.productPrice | currency}}</h4>
<h4>
<a href="#">{{x.productName}}</a>
</h4>
<p>{{x.productDesc}}.</p>
</div>
<div class="ratings"> {{x.ReviewProducts| ratingavg:'ratingReview'}}</div>
</div>
</div>