Search code examples
javascriptangularjsnavigatorisolate-scope

isolate scope angular binding not updated from geolocation


I'm using isoated scope in a directive. Everything seems to work fine. I set a = scope on two properties and bind to them in my template. Then, in my controller I call my service, get the data and push it onto the bound objects.

What is really wigging me out is that I can both log and set a break point and can see the data, but angular doesn't update the binding (although it updates my bool field just fine).

I've provided a plunkr: http://plnkr.co/edit/8sVwaea5Amqvf3yiI1Nm?p=preview

And the relevent code portion is:

  if (navigator.geolocation) {
    //navigator.geolocation.getCurrentPosition(success, fail);
    $timeout(function() { success({testdata: "bogusdata"}) }, 1500);
  } else {
    fail({ error: "navigator.geolocation not available"});
  }

Clearly, if I use my $timeout mock, it works just fine. But if I substitute the getCurrentPosition function, nothing updates (but it DOES LOG)?!?!

Help?


Solution

  • Actually you only have a problem with the way you're trying to handle the data - the Geolocation object arrives and gets put on the $scope correctly, it's only that JSON.stringify serializes it (seemingly incorrectly) into a {}.

    You can verify this by logging $scope.locationData.payload - you will see the entire object appear on the console, and logging typeof $scope.locationData.payload.coords shows object, which means that it is populated properly at the time of the log call. (Logging the object itself would not be proof of this, because console.log is only logging object references, asynchronously accessing them when you expand them manually)

    This is only seemingly incorrect, because JSON.stringify is only supposed to log the own properties of an object, and coords and timestamp are not own properties of this Geolocation object. (try $scope.locationData.payload.hasOwnProperty('coords'): it returns false)

    The workaround will depend on your exact needs. Maybe you don't even need a workaround, because you can access this data, just can't log or stringify it the way you wanted.

    Additional resources: