NICKO
NICKO

Reputation: 33

angular js $scope not holding json values

Angular is loosing my my JSON values, and i'm trying to find out why. I think I need to make a promise or a time out, or maybe apply. I'm not quite sure...

angular version: 1.2.1

 galleryApp.controller('GalleryCtrl', function ($scope, $http, $routeParams, $filter){
    $http.get('mygallery.json').success(function(data) {

        $scope.gallery = data;

        //DISPLAY: CONTENTS OF JSON IN OBJECT : WORKS 
        console.log($scope.gallery);
    });

    //DISPLAY: undefined : DOES NOT WORK AS EXPECTED
    console.log($scope.gallery);

    //DISPLAY: CONTENTS OF OBJECT: I can see scope.gallery exists!
    //I just can't seem to access scope.gallery directly outside of http.get()
    console.log($scope);

  });

Note: scope.gallery or "gallery" works perfectly fine in my view! {{gallery.name}} etc.

It seems like there is some behind the scenes things angular is doing to the scope, or some concept that i'm not quite grasping.

Upvotes: 1

Views: 111

Answers (2)

jelinson
jelinson

Reputation: 845

The result of http.$get is a promise (specifically an HtmlPromise, see the $http docs). A promise is described as the following in the $q docs:

an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time

The success method of an HtmlPromise takes a callback function to run once the promise is resolved (meaning the action is complete). The anonymous function thus runs asynchronously. When it is logged outside of the callback, the callback has not yet been run and therefore the scope variable has not been set.

I imagine the view is as expected because the http request completes and the view is updated so fast, it is imperceivable.

Upvotes: 0

Alexander Kalinovski
Alexander Kalinovski

Reputation: 1409

Well, it's trivial as $http.get is an asynchronous operation. So while it is working the rest of the code will be finished. If you log the $scope.gallery it is undefined yet. If you log the $scope it's still undefined but will be updated when the success callback is invoked. Th reason of this effect for you is just feature of console.log which writes not the current snapshot but the object itself so if changed the output of the console will be updated respectively. But in general none of your code outside of the $http.get will work as you expected here. So you should either use the success callback or use $watch to track the changes.

Also refer to this documentation: $http, $q

Upvotes: 1

Related Questions