Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs loop trought $http.post

When I loop through the $http post service for Angularjs

for (var i = 0; i < $scope.tagStyles.length; i++) {
  $scope.profilTag.tag = $scope.tagStyles[i].id_tag;
  $scope.profilTag.texte = $scope.tagStyles[i].style ;
  $scope.profilTag.profil = lastDocId;

  $http.post('/ajouterProfilTag',$scope.profilTag) 
  .success(function(data){ 
    if (data=='err'){ 
      console.log("oops"); 
    }     
  });
};

I get just the last element in my database. Is it something related to asynchronous call ?

like image 964
badaboum Avatar asked Jun 08 '26 22:06

badaboum


2 Answers

$http docs:

The $http service will not actually send the request until the next $digest() is executed.

What probably happens is that $scope.profilTag is being passed by reference to $http and only being sent after a $digest. You override that reference each iteration and that's why you only left with your last item.

Be aware that functions has scopes but for loops don't!

Try this instead:

$scope.tagStyles.forEach(function(item){
  var profilTag = {
    tag: item.id_tag,
    texte: item.style,
    profil: lastDocId,
  };

  $http.post('/ajouterProfilTag',profilTag) 
  .success(function(data) { 
    if (data=='err'){ 
      console.log("oops"); 
    }
  });

});
like image 53
Ilan Frumer Avatar answered Jun 10 '26 11:06

Ilan Frumer


You may want to use AngularJs promise API.

var promiseArray = [];

for (/*your loop statements*/) {
 promiseArray.push($http.post('/url', $scope.var));
}

$q.all(promiseArray).then(function(dataArray) {
    // Each element of dataArray corresponds to each result of http request.
});

See Usage->returns section in $http service docs, to understand what is returned via dataArray parameter.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!