下面是一个的jsfiddle,显示我想要做的事: http://jsfiddle.net/P3c7c
Here's a jsFiddle that shows what I'm trying to do: http://jsfiddle.net/P3c7c
我使用的是谷歌的地方自动完成小工具来获取纬度/经度坐标,然后我希望在随后的搜索功能使用。这似乎是正确的方式来实现这一点,考虑到需要一个事件侦听器添加到一个元素,是使用一个指令,并附加使用指令的链接功能的监听器。然而,这个监听器里面,我需要它来设置SearchForm控制器,这是其父母的位置属性。我还没有想出如何使这一连接。这里是code的相关大块:
I'm using the Google Places AutoComplete widget to obtain lat/long coordinates, which I then wish to use in a subsequent search function. It seemed that the proper way to implement this, considering the need to add an event listener to an element, was to use a directive, and to attach the listener using the directive's linking function. However, inside of this listener, I need it to set the location property of the SearchForm controller, which is its parent. And I have not figured out how to make that connection. Here's the relevant chunk of code:
/* 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;
});
}
}
});
先谢谢了。
推荐答案
两处微小的修改,它应该工作:
Two minor corrections and it should work:
<google-places location="location"></google-places>
和当您将指令集内的位置你也需要做 $范围。$适用()
and when you set location inside your directive you also need to do $scope.$apply()
$scope.$apply(function() {
$scope.location = location;
});
您需要做的 $适用()
,因为事件发生角消化循环之外,所以你必须让角度知道有什么东西的范围内变化,它需要消化这是双向绑定和其他内部异步的东西。
You have to do $apply()
because the event happens outside of angular digest loop, so you have to let angular know that something has changed inside the scope and it needs to "digest" it's bi-directional bindings and other internal async stuff.
另外,我不认为你需要 transclude:真正的
Also, I don't think you need transclude:true
.
http://jsfiddle.net/P3c7c/1/
相关推荐
最新文章