AngularJS access variable inside $ http.get

app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    $http.get(something.json).success(function(data){
      $scope.entries = data;
    });
    abc = $scope.entries.timestamp;  <-- not working
}]);

      

After searching, it turned out that $ http is an asynchronous function. So I am migrating it into a function, but still not working.

app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    var getEntries = function(){ return
      $http.get(something.json).success(function(data){
        return data;
      });
    };

    $scope.entries = getEntries();
    console.log($scope.entries); // returns undefined
}]);

      

+3


source to share


1 answer


Your console.log gets fired before your promises have any doubts. Place console.log on success.

I would probably write it like this:

var getEntries = function(){ 
      $http.get(something.json).success(function(data){
        $scope.entries = data;
        console.log($scope.entries);
      });
    };

    getEntries();

      



Also, if it still seems like there is a problem, console.log (data) and see what you get. It might be a source code issue.

Here is a plunker that shows what I mean. You don't need to wrap it in a function like you. $ http.get already has a function.}

+1


source







All Articles