Sebastialonso
Sebastialonso

Reputation: 1461

$scope not behaving correctly when I try to get a variable

I have a service, ThingsService, which speaks to my API. I also have a SharedData Service, following this great answer. As far I can tell and test, SharedData is not the issue.

The controller, ThingsController uses this service to bring data into the application, like this:

$scope.getThing = function(id){
  ThingsService.GetThing(id,
    function(response){
      $scope.thing = response;
    },
    function(){
      alert("Error");
    });
};

$scope.getThing(SharedData.getNextThingId());
console.log($scope.thing); // => undefined
console.log($scope); // => thing, among others

Now, when I try to access $scope.thing it returns undefined. The funny thing is that if I do something like console.log($scope), there is an object called thing, and moreover all proper data is set within this object.

Does anyone has a clue what is going on? I'm quite certain I missed something.

UPDATE: Following Mathew's asnwer, this snippet

$scope.getThing = function(id){
  ThingsService.GetThing(id,
    function(response){
      $scope.thing = response;
      $scope.doStuffwhenThingIsReady(); //<- Here $scope.thing is set :)
    },
    function(){
      alert("Error");
    });
};

saves the day.

Upvotes: 0

Views: 24

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

It's most likely because ThingsService.getThing is happenning outside of angular (via a post or what have you) so console logging directly afterwards isn't showing it. If you console log the $scope though it's a reference and so when you open it up you'll see it as the ThingsService.getThing is probably complete by then. You'll have to wait until ThingsService.getThing is done until you can use $scope.thing.

Upvotes: 1

Related Questions