当我使用数据绑定时,角度地理编码器失败

时间:2015-12-03 20:34:01

标签: javascript angularjs

我使用的是:http://jasonwatmore.com/post/2014/02/15/AngularJS-Reverse-Geocoding-Directive.aspx

基本上,我使用它时工作正常:

mongodb

但是,这是问题..

当我这样的时候:

<reverse-geocode lat="40.730885" lng="-73.997383" />

它不能使用{{vm.user.location [1]}}和{{vm.user.location [0]}}的值,因为由于某种原因它传递0而不是真实值..

当我将其键入跨度时,值就会很好。

<reverse-geocode lat="{{vm.user.location[1]}}" lng="{{vm.user.location[0]}}"></reverse-geocode>

我不确定发生了什么:(

为什么它认为我传递的值为0而不是我的数据库中的实际lat / long值?

1 个答案:

答案 0 :(得分:1)

您需要观察属性更改,因为您正在动态加载位置数据,因此您还需要指令在这些值更改时进行更新。

以下是添加观察行为的方法:

.directive('reverseGeocode', function ($timeout) {
    return {
        restrict: 'E',
        template: '<div></div>',
        link: function (scope, element, attrs) {

            attrs.$observe('lat', geoCode);
            attrs.$observe('lng', geoCode);

            function geoCode() {
                $timeout(function() {
                    var geocoder = new google.maps.Geocoder();
                    var latlng = new google.maps.LatLng(attrs.lat, attrs.lng);
                    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[1]) {
                                element.text(results[1].formatted_address);
                            } else {
                                element.text('Location not found');
                            }
                        } else {
                            element.text('Geocoder failed due to: ' + status);
                        }
                    });
                });
            }
        },
        replace: true
    }
})

演示: http://plnkr.co/edit/PehccH32xMzlbhsRD0FI?p=info