Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: returning data from a function and assigning it to a variable

I am new to angularjs, and I am trying to return the data from a function to another function, and store it in a variable.

$scope.myNameValidate = function(name){
    $scope.friendsList = $scope.getAllFriends(name);
    console.log("data", $scope.friendsList);
}

$scope.getAllFriends = function(name){
    friendService.getAllfriends(name) 
    .then(function(data){
        //success
        console.log(data);
    }, function(err){
        //error
    })
}

I want to store all the objects in a variable but I get undefined as result.

output in console

data undefined

[Object, Object, Object, Object, Object, Object]

like image 909
Raghav Avatar asked Aug 10 '16 08:08

Raghav


1 Answers

You need to know the Angular promise.

This issue related to Asynchronous operation.

You can fix it with proper thenable chaining. You can do it in this way.

$scope.myNameValidate = function(name) {
    $scope.getAllFriends(name)
        .then(function(data) {
            $scope.friendsList = data;
            console.log(data);
        }, function(err) {
            //error
        });

}

$scope.getAllFriends = function(name) {
    return friendService.getAllfriends(name)

}
like image 88
RIYAJ KHAN Avatar answered Oct 12 '22 23:10

RIYAJ KHAN