nsr nsr - 3 months ago 8
AngularJS Question

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

Am new to angularjs, am trying to return the data from a function to another function and storing 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 am getting as undefined

output in console

data undefined

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

R.J R.J
Answer

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)

}