0

I'm trying to update a field with a new geo code value, but even though the model is updated it is not binding with first call. My controller code is as follows:

function TheReportCtrl($scope) {
    $scope.code = [];
    $scope.code.lat = "19.2555500";
    $scope.getCode = function () {
        var geocoder = new google.maps.Geocoder();
        var address = "12323 Barker Cypress Rd, Cypress, Texas"
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                $scope.code.lat = results[0].geometry.location.k;
            } else {
                console.log("Geocoding failed: " + status);
            }
        });
    }
} 

What is the missing part of my code?

Here is the JsFiddle Code Sample

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
Gayan
  • 2,750
  • 5
  • 47
  • 88
  • 1
    You need to call `$scope.$apply();` after `$scope.code.lat = results[0].geometry.location.k;`. AngularJS does not know you changed the scope otherwise. – Sergiu Paraschiv Aug 21 '14 at 14:43
  • thanks Sergiu Paraschiv unfortunately your answer is in comment. :) – Gayan Aug 21 '14 at 15:10

2 Answers2

2

You've missed an $scope().$apply();

See http://fiddle.jshell.net/yfLek2cw/

Also your Angular CDNLink inside your original fiddle doesn't work. The reason is, that the geolocation callback is done not from angular. Therefore the dirty check mechanism doesn't work there. To start the dirty check again, you've to call $scope.$apply();

This is needed for ALL external callback functions, even if those callbacks are inside the angular scope. Auto $apply only works for angular callbacks like $timeout or the $q service

PArt
  • 1,762
  • 1
  • 9
  • 14
0

Your code is actually working, you just need to update the $scope by using the $apply() method. Here's a fiddle:

http://fiddle.jshell.net/7v2dfLsv/3/

bencripps
  • 2,025
  • 3
  • 19
  • 27