0

I am trying to fetch data from mongodb using express to angular inside a for loop. I can access data inside this get instance but not outside of it. Here is my code

var daily_jobs=[];
$http.get(mongodUrl).then(function(response) {
    var allMachinename = response.data;
    daily_jobs=[];
    for(var i = 0;i<allMachinename.length;i++){
        $scope.masch_name.push({name:allMachinename[i].name,id:allMachinename[i].id,daily_jobs:[]});
        $http.get(mongodUrl+'getmaschdata/'+$scope.input_id+'/'+allMachinename[i].id).then(function(jobs) {
            if(jobs.data.length > 0){
                daily_jobs= jobs.data;
            }
            console.log(daily_jobs[0].job_name);
            },function(err){
                console.log(err);
        }); 
        $scope.masch_name[i].daily_jobs= daily_jobs;
    }
},function(err){
    //console.log(err);
});

The variable daily_jobs is global, but when I want to access it outside the get function it always remain empty. How can I get that value outside of second http.get function? Any help will be appreciated. Thanks.

  • you should probably look at [promises](https://toddmotto.com/promises-angular-q) for this sorta thing – Jax Dec 24 '17 at 12:14

1 Answers1

0

I couldn't get a clear picture what are you trying to achieve why are you making two http get inside a controller rather than making as a service. however to answer your question replace this

 daily_jobs= jobs.data;

with

 $scope.masch_name[i].daily_jobs = jobs.data;

that should work if you want to know more about this read here

Angular Share Variable betwen $http.get and controller

I will suggest you to read about services in AngularJS and $scope.apply as well for more detail

Kannan T
  • 1,639
  • 5
  • 18
  • 29