I am just learning to use JavaScript, AngularJS, and Parse, so please, if I am improperly doing anything, say so. I want to learn as much as possible.
I have an assignment where I am instructed to use Parse and AngularJS. I want to display each company in my companies object, and then the rating that each one has. In Parse these are stored as two separate objects with a relation.
I've finally been able to get the ratings calculated, however Angular is overwriting the data for the ratings. It is displaying the last rating calculated, rather than each rating. The console.log(total) is producing accurate numbers in the console.
Here is the code inside my controller for retrieving companies:
function getCompanies() {
new Parse.Query(Companies).find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
results[i].relation("ratings").query().find({
success: function(ratings) {
// retrieve stars and calculate average rating
var total = 0;
for (var o = 0; o < ratings.length; o++) {
var stars = parseInt(ratings[o].attributes.stars);
total += stars;
}
total = total / ratings.length; // get average rating
$scope.$apply(function() {
$scope.companies = results.map(function(obj) {
console.log(total); // produces correct results
return {name: obj.get("name"), rating: total, parseObject: obj};
})
});
}
});
}
}
});
}
In my view I am using the following code:
<div ng-repeat="company in companies">
<h1>{{company.name}}</h1>
<h3>Rating: {{company.rating}}</h3>
</div>
Right now, if I had two companies and they had ratings of 2 and 4, right now Angular displays 4 for both. However, the console.log(total) will display 2 and 4.
If my code is way off, please tell me, I want to learn as much as possible. Any help is greatly appreciated, thank you.
can you try a code something like below,
success: function(results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
results[i].relation("ratings").query().find({
success: function(ratings) {
//calculate total here;
//var total = your logic to calculate the total
//then store the total in the result object
result.total = total;
}
})
}
$scope.$apply(function() {
$scope.companies = results.map(function(obj) {
console.log(total); // produces correct results
return {name: obj.get("name"), rating: obj.total, parseObject: obj};
})
});
}