-3

How to display reponse data (get) from server in AngularJS

in my code I need to alert $scope.orders inside that controller but it willll not show..

function OrderController($scope,$http)
{
    var orderPromise = $http.get("../api/order");

    orderPromise.success(function(data, status, headers, config) 
    {
        $scope.orders=data
        alert(JSON.stringify($scope.orders))  // First alert 
    });

    orderPromise.error(function(data, status, headers, config) 
    {
        alert("Error");

    });

    alert(JSON.stringify($scope.orders))    // Second alert 
}

How can i access $scope.orders to outside the success fun() Here I am alerting $scope.data in two times In here First Alert is shown but Second Alert is nothing to show why? How to show second one?

2
  • 1
    Possible duplicate of AngularJS : Scope issue in $http success callback Commented Feb 9, 2016 at 15:05
  • The reason the first alert works but the second one does not is because the execution of the first is delayed until the promise is successfully fulfilled... that can take anywhere from milliseconds to seconds, depending on the request. However, the second one is executed almost immediately after the controller is instantiated since it is run right after the promise handlers are defined (not executed). What exactly are you trying to do with the data? If you just want to display it, then bind the $scope.orders in you view, and it will automatically display after the promise resolves. Commented Feb 9, 2016 at 15:06

1 Answer 1

1

Second alert will not show because there's nothing in $scope.orders when you alert it. That's the nature of asynchronous calls, only when you enter the success/error sections will you have something there (or not...).

Until the server returns your response and the success/error functions trigger, that variable is still unpopulated since $scope.orders=data hasn't run.

You should read the docs for some more info, and get some deeper understanding into how promises work.

4
  • AOmri how can I access these $scope.orders second time any solution for that...Thnakyou.I am beginner consider me Commented Feb 9, 2016 at 15:09
  • @symonkt1 You can't, from the reason I mentioned. Only inside success. Commented Feb 9, 2016 at 15:22
  • Oh ok Omri I got it i read doc Thankyou for your comments..One more thing can i push this to factory and call back to same controlller? Commented Feb 9, 2016 at 15:35
  • @symonkt1 Yep, preferred even. Commented Feb 9, 2016 at 16:03

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.