Jan sebastian Jan sebastian - 3 months ago 7
AngularJS Question

Angularjs: loop $http.post

script.js

for(var i = 0;i<$scope.data_acc_lv.length;i++)
{
var input3 = {
"_id": $scope.accLvID + i,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].names,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute,
}
$http.post("http://localhost:1234/access_menu",input3)
.success(function(res){
if(res.error == 0)
{

}

});
}


script.js

app.post('/access_menu',function(req,res){
var IDMenu = req.body._id;
var Forein = req.body.acc_id;
var Name = req.body.name;
var Read = req.body.read;
var Execute = req.body.execute;

var data = {"error":1,"Access_menu":""};
if(!!Name && !!Read && !!Execute)
{
db.collection("access_menu").insert({_id:IDMenu,acc_id:Forein,name:Name,read:Read,execute:Execute},function(err,req){
if(!!err)
{
data['Acess_menu'] = "input error";
}
else
{
data['error'] = 0;
data['Access_menu'] = "input berhasil"
}
res.json(data);
});
data = {"error":1,"Access_menu":""};
}
});


so I trying to input data from table to database but I always got the value from the last index (all previous value replace by the last index value), so what the cause the problem. Thank you

Answer

You can wrap the code inside the for loop in an immediately invoked function

     (function( i ) {
        var input3 = {
            "_id": $scope.accLvID + i,
            "acc_id":$scope.accLvID,
            "name": $scope.data_acc_lv[i].names,
            "read": $scope.data_acc_lv[i].read,
            "execute": $scope.data_acc_lv[i].execute,
        }
        $http.post("http://localhost:1234/access_menu",input3)
        .success(function(res){
            if(res.error == 0)
            {

            }

        });

      })(i);

Hope this helps.