0

The following code is in my controller - when I reach the console.log() line, nothing is printed out. The AJAX call returns a valid array. I tried using $scope.$apply but I got an process already in progress error, I'm assuming because using $http automatically starts the digest cycle:

var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController',  TasksController);
 function TasksController($scope, $http) {
$scope.transactions = [];
$http.get('transactions').then(function (response) {
             $scope.transactions = response.data;     
     }, function (error) {
         throw error;
     });
console.log($scope.transactions);
}
Paymon Wang-Lotfi
  • 545
  • 2
  • 11
  • 29

2 Answers2

2

$http.get is asynchronous. When you call your console.log, your GET request didn't return yet. You can move it inside the handle body to see that it works:

$http.get('transactions').then(function (response) {
             $scope.transactions = response.data;     
             console.log($scope.transactions);
     }, function (error) {
         throw error;
     });
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
1

You should know that AJAX calls made with $http in AngularJS are asynchronous, that is, they do not run in sequence with the rest of the code, unless you set it that way.

Therefore when the console.log is executed, the request still has not finished processing. The correct thing is that you run console.log after performing the assignment of the variable in the AJAX call, in this way:

var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController',  TasksController);
function TasksController($scope, $http) {

    $scope.transactions = [];

    $http.get('transactions').then(function (response) {
        $scope.transactions = response.data;
        console.log($scope.transactions);     
    }, function (error) {
        throw error;
 });
}
Cristiam Mercado
  • 573
  • 12
  • 34