I run a factory in my code to fetch data from an API and store the results in a variable. However, every time I try to access the variable, it returns as undefined. Is there a way to pass the results of an async call to a variable? In my scenario, the structure of my factory is as follows.
angular.module('MyApp.services', [])
.factory('ReportService', ['$http', '$window', '$upload', 'AuthService', function ($http, $window, $upload, AuthService) {
return {
findAll: function (criteria) {
criteria = criteria || [];
return $http.get(BASE_URL + '/ajax.php?action=reports.all&' + criteria.join('&'));
}
}
}])
Then, in the controller section
.controller('MyViewController', [
'$scope', 'ReportService', 'toaster', '$modal', '$rootScope',
function ($scope, ReportService, toaster, $modal, $rootScope) {
ReportService
.findAll()
.then(
function success(response, status, headers, config) {
$scope.reports = response.data.reports;
},
function error(response, status, headers, config) {
console.log('error');
});
//console.log($scope.reports) returns undefined here.
}
]);
Is there any method to ensure that the variable is populated at the global level for the controller?