1

Here is my controller:

$scope.mainModel = getReviews({model:mainModelArr[1]}); $scope.compareModel = getReviews({model:compareModelArr[1]}); function getReviews(data) { $http.post(url, data) .success(function(res) { formatReviews(res) }) .error(function(err) { console.log("Something went wrong: "+err); }); } function formatReviews(data) { var review = data[0]; review.sumReviews = (review.sumReviews/review.ratingAvg).toFixed(0); review.sumRecommend = (review.sumRecommend/review.sumReviews*100).toFixed(1); review.ratingAvg = (review.ratingAvg).toFixed(1); console.log(review); // logs message fine return review; } 

These functions work fine, logs review var., but somehow it didn't assign review variable neither to $scope.mainModel nor to $scope.compareModel.

NOTE: I know that it wasn't assigned, because it's never showed up in HTML:

<p>{{mainModel}}</p> 

What did I do wrong and how can I fix that?

1

2 Answers 2

1

Ajax requests works Async, angularjs use promises to handle this requests

$scope.mainModel = undefined; $scope.compareModel = undefined; getReviews({model:mainModelArr[1]}).success(function(res){ $scope.mainModel = formatReviews(res); }); getReviews({model:compareModelArr[1]}).success(function(res){ $scope.compareModel = formatReviews(res); }); 

If you return post request, you can handle it anywhere, where you call getReviews method

function getReviews(data) { return $http.post(url, data) .error(function(err) { console.log("Something went wrong:", err); }); } function formatReviews(data) { var review = data[0]; review.sumReviews = (review.sumReviews / review.ratingAvg).toFixed(0); review.sumRecommend = (review.sumRecommend / review.sumReviews * 100).toFixed(1); review.ratingAvg = (review.ratingAvg).toFixed(1); console.log(review); // logs message fine return review; } 
Sign up to request clarification or add additional context in comments.

1 Comment

@MichaelVayvala i used success not then
1

Since asynchronous code won't allow you simply return the value, you should work with promises using their then methods:

getReviews({model: mainModelArr[1]}).then(function(data) { $scope.mainModel = data; }); getReviews({model: compareModelArr[1]}).then(function(data) { $scope.compareModel = data; }); function getReviews(data) { return $http.post(url, data) .success(formatReviews) .error(function(err) { console.log("Something went wrong: "+err); }); } 

1 Comment

@MichaelVayvala Ops, forget to return from getReviews.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.