yevhensh
yevhensh

Reputation: 410

Angular $resource, lose scope variable after function call

 var createAttendances = function(){
    var stud = StudentResource.get(function(data){
        $scope.students = data.students;
        console.log($scope.students);
    });
    console.log(stud.students);
    console.log($scope.sudents);
};

inside resource get function it prints out Array of two objects (which is good) outside resource get it prints out undefined

it sees stud object but when i query to students params it returns undefined

as u can see main problem is to get $scope.students or data.students ouside StudentResouce.get func

Upvotes: 0

Views: 302

Answers (2)

victor sosa
victor sosa

Reputation: 899

This is an async call, so you can get result in this way, I got the same confusion in the beginning too.

StudentResource.get().$promise.then(function (result) {
       $scope.students = result.students;
        console.log($scope.students);
})

Upvotes: 0

MeanMan
MeanMan

Reputation: 1090

StudentResource.get

is an async call, which means the lines below it can get executed even before the Resource GET call is completed, that is the reason why your variables are returning undefined outside the callback.

to access the data you fetched through GET call, you have to query it inside the call back itself.

Upvotes: 2

Related Questions