2

I have created an AngularJS directive to wrap a Geocomplete plugin for Google Maps Autocomplete. I'm trying to make it bind to a property of the scope, which is specified by adding a 'geocomplete' attribute to an existing element.

    geocompleteModule.directive("geocomplete", function ($log, $timeout, $compile, $controller) {
        return {
            restrict: 'A',
            priority: 200,
            link: function (scope, element, attrs, ctrl) {
                var autocomplete = $(element).geocomplete().bind("geocode:result", function (event, result) {
                    if(result.geometry && result.geometry.location) {
                        var location = result.geometry.location;
                        scope.$apply(function (s) {
                            s[attrs.geocomplete] = new Models.Point(location.lat(), location.lng());
                        });
                    }
                });
            }
        };
    });

However, if the property referred to in the geocomplete attribute is a sub-property, this won't work. For example:

<input geocomplete="location" />

Works.

<input geocomplete="search.location" />

Will not work.

Natively, AngularJS seems to be able to do this with its own bindings, but how would I go about implementing this myself?

Edit

I know how this can be done using a split and for loop, but presumably this isn't the "proper" way.

2 Answers 2

2

Just two changes I can see for your directive. Added scope, binding any value on the geocomplete attribute to 'location' then use s[scope.location] in your scope.$apply

Directive documentation: http://docs.angularjs.org/guide/directive

geocompleteModule.directive("geocomplete", function ($log, $timeout, $compile, $controller) {
 return {
    restrict: 'A',
    scope:{
      location:'=geocomplete'  
    },
    priority: 200,
    link: function (scope, element, attrs) {
        var autocomplete = $(element).geocomplete().bind("geocode:result", function (event, result) {
            if(result.geometry && result.geometry.location) {
                var location = result.geometry.location;
                $timeout(function() {
                    scope.location = new Models.Point(location.lat(), location.lng());
                });
            }
        });
    }
 };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Jason, this answer is nearly, but not quite there. I've updated it to fix it.
0
s[attrs.geocomplete] = new Models.Point(location.lat(), location.lng());

Replace like:

var a = function(){};
var s = [];

s.push( { 'attr' : 'aaa.bbb', 'method' : new a() } );

1 Comment

I'm sorry, but this makes no sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.