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.
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());
});
}
});
}
};
});
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() } );