3
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, found that $http is an asynchronous function. So I wrap it in to 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
}]);
0

1 Answer 1

1

Your console.log is firing before your promises return no doubt. Put the console.log inside the 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 there is an issue, console.log(data) and see what you get. It may be a back-end issue.

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

Sign up to request clarification or add additional context in comments.

8 Comments

I want to use the variable $scope.entries somewhere inside the controller, not just inside the success
you can. it's $scope.
Anything you make a property of $scope is available anywhere in the controller, and can be bound to the view.
How? I tried to use $scope.entries outside the $http.get but its returning undefined
The question is when? Bind {{entries}} to your view, then make your ajax call using the code I supplied, and see if it updates.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.