我想从评论中获得平均评分并显示,但我不确定如何做到这一点。
JSON
"Reviews":[
{
"OwnerID":1,
"Comment": "Charlotte is brilliant. A lovely person. Thank you!",
"rating":4
},
{
"OwnerID":2,
"Comment": "The best dog carer ever! She is amazing",
"rating":4
}
],
html文件
<ion-item ng-repeat="item in PetCareProfile>
<span ng-repeat="rate in item.Reviews" class="item-text-wrap"> {{calculateAverage(rate.rating)}} </span>
</ion-item>
控制器
.controller('CareTakerProfileCtrl',
function($scope,$http,$stateParams,$ionicPopup, ionicDatePicker)
{
$http.get('js/SampleJson.json').success(function (data) {
$scope.PetCareProfile = data.PetCareTakers;
$scope.whichPetCareProfile = $stateParams.aId;
$scope.calculateAverage = function(MyData){
var sum = 0;
for(var i = 0; i < MyData.length; i++){
sum += parseInt(MyData[i], 10); //don't forget to add the base
}
var avg = sum/MyData.length;
return avg;
};
})
结果: NaN NaN NaN
我想要的: 4.3333333
答案 0 :(得分:1)
您可以将数组传递给函数并使用angular.forEach()
计算平均值 <li ng-repeat="item in PetCareProfile">
{{calculateAverage(item)}}
</li>
<强>样本强>
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.PetCareProfile = [{
"Reviews": [{
"OwnerID": 1,
"Comment": "Charlotte is brilliant. A lovely person. Thank you!",
"rating": 4
}, {
"OwnerID": 2,
"Comment": "The best dog carer ever! She is amazing",
"rating": 4
}]
}]; //
$scope.loopcount = 0;
$scope.calculateAverage = function(MyData) {
$scope.sum = 0;
var filterData = MyData.Reviews;
angular.forEach(filterData, function(val) {
$scope.sum += val.rating;
});
var avg = $scope.sum / filterData.length;
return avg;
};
}
]);
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap@3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap@3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />
<link data-require="bootstrap@3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
<script data-require="jquery@1.11.3" data-semver="1.11.3" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script data-require="bootstrap@3.3.5" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="item in PetCareProfile">
{{calculateAverage(item)}}
</li>
</ul>
</div>
</body>
</html>
答案 1 :(得分:0)
您是否尝试过:
<ion-list>
<ion-item ng-repeat="item in PetCareProfile>
{{item.rating}}
</ion-item>
</ion-list>
但如果你想(只在IONIC中)你也可以使用(而不是ng-repeat)
<ion-content>
<ion-item collection-repeat="item in PetCareProfile">
{{item.rating}}
</ion-item>
</ion-content>