这是一个 jsFiddle,它显示了我正在尝试做的事情:http: //jsfiddle.net/P3c7c
我正在使用 Google Places AutoComplete 小部件来获取纬度/经度坐标,然后我希望将其用于后续搜索功能。考虑到需要向元素添加事件侦听器,似乎实现这一点的正确方法是使用指令,并使用指令的链接函数附加侦听器。但是,在这个监听器内部,我需要它来设置 SearchForm 控制器的 location 属性,它是它的父级。而且我还没有弄清楚如何建立这种联系。这是相关的代码块:
/* Controllers */
function SearchForm($scope){
$scope.location = ''; // <-- this is the prop I wish to update from within the directive
$scope.doSearch = function(){
if($scope.location === ''){
alert('Directive did not update the location property in parent controller.');
} else {
alert('Yay. Location: ' + $scope.location);
}
};
}
/* Directives */
angular.module('OtdDirectives', []).
directive('googlePlaces', function(){
return {
restrict:'E',
replace:true,
transclude:true,
scope: {location:'=location'}, // <--prob something wrong here? i tried @/& too, no luck
template: '<input id="google_places_ac" name="google_places_ac" type="text" class="input-block-level"/>',
link: function($scope, elm, attrs, ctrl){
var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
// THIS IS THE STRING I WANT TO SAVE TO THE PARENT CONTROLLER
var location = place.geometry.location.lat() + ',' + place.geometry.location.lng();
// THIS IS NOT DOING WHAT I EXPECT IT TO DO:
$scope.location = location;
});
}
}
});
提前致谢。