AngularJS: returning data from a function and assigning it to a variable
Solution 1
You need to know the Angular promise.
This issue related to Asynchronous operation.
You can fix it with proper then
able 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)
}
Solution 2
Why its' undefined?
Your function $scope.getAllFriends()
is not returning anything witch can set data to $scope.friendsList.
function myFunc(){
var i = 5;
}
var myVar = myFunc();
myVar will not have value 5.
function myFunc(){
var i = 5;
return i;
}
var myVar = myFunc();
In angular even if it's asynchronous data when you set to $scope as soon data has arrived angular will update your view and scope.
Solution 3
You cannot use async callbacks this way. In your particular case you should set $scope.friendsList inside the success callback.
$scope.myNameValidate = function(name) {
$scope.getAllFriends(name);
}
$scope.getAllFriends = function(name) {
friendService.getAllfriends(name)
.then(function(data) {
$scope.friendsList = data;
console.log("data", $scope.friendsList);
}, function(err){
//error
})
}
Solution 4
$scope.myNameValidate = function(name){
$scope.friendsList = $scope.getAllFriends(name)
.then(function(data){
//here is your data
})
.catch(error){
//Error
}
console.log("data", $scope.friendsList);
}
$scope.getAllFriends = function(name){
var promise = friendService.getAllfriends(name)
.then(function(data){
return data;
}, function(err){
//error
})
return promise;
}
This is asynchronus call thats why you got undefined
Raghav
Updated on December 24, 2020Comments
-
Raghav over 3 years
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]