-2

Controller Page

    $scope.page = {
        '1' : "small",
        '2' : "large",
        '3': "medium"
    };      
    $scope.form.appraisal_id = "abc123";
    $scope.form.user_id = "efg123";
    for(var prop in $scope.page){
        $scope.form.question_id = prop;
        $scope.form.answer = $scope.page[prop]
        console.log($scope.form);
        appraisalService.saveForm($scope.form,function(result){
          $scope.sent=result
          console.log($scope.sent)
          });



};

My Result

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "1", answer: "small"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "2", answer: "large"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "3", answer: "medium"}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Expecting output

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "1", answer: "small"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "2", answer: "large"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "3", answer: "medium"}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 1, answer: "small"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 2, answer: "large"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3,answer: "medium"…}

Manju John
  • 21
  • 1
  • 10

1 Answers1

0

Try using $q.

var promises = [];

for(var prop in $scope.page) {
    $scope.form.question_id = prop;
    $scope.form.answer = $scope.page[prop]

    promises.push(appraisalService.saveForm($scope.form, function(result){
      return result;
    }));
}

$q.all(promises).then(function(result) {
  console.log(result);
});

Your appraisalService call is async, so the loop is complete before even the first async call has time to complete (so it's only catching the last call).

You can instead push each promise of the appraisalService to an array, and then use $q.all to wait until all promises have resolved before logging the result (or doing whatever you want with it.)

If you're not familiar with $q, it comes with Angular. Just inject it.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68