我有一个函数 $scope.addReport()
,它应该执行以下操作:
- 在点击时添加事件监听器以添加新标记(通过执行 placeMarker(location))
- 用新坐标更新
$scope.TempMarker
模型 - 显示带有
ng-show="showForm'
指令的表单 - 移除监听器,以便只能放置一个标记
我遇到的问题是,如果我尝试在监听器中更改 $scope.showForm
,它不会更新范围,它仅在监听器中评估为 true。如果我将它移出监听器,则范围会更新并显示表单。
所以我的问题是为什么作用域没有为 $scope.showForm
更新,而是为 $scope.TempMarker
更新,我如何在监听器中更新它?
代码如下:
//attached to ng-show directive
$scope.showForm = false;
//this function creates a marker based on passed location
function placeMarker(location) {
$scope.tempMarker = new google.maps.Marker({
position: location,
map: $scope.map,
draggable: true
});
}
//this is executed on addReport() click
$scope.addReport = function() {
//$scope.showForm = !$scope.showForm; ---> if declaration is here, scope is updated and the form is shown
var newMarkerListener = google.maps.event.addListener($scope.map, 'click', function(event) {
placeMarker(event.latLng); // create the actual marker
//update the new report object
$scope.newReport.lat = event.latLng.lat();
$scope.newReport.lng = event.latLng.lng();
$scope.showForm = !$scope.showForm; // -----> not updating the scope
console.log($scope.showForm) // logs true
google.maps.event.addListener($scope.tempMarker,'dragend',function(event) {
$scope.newReport.lat = event.latLng.lat();
$scope.newReport.lng = event.latLng.lng();
});
google.maps.event.removeListener(newMarkerListener);
});
}
最佳答案
尝试用 $apply 包装它
$scope.$apply(function () {
$scope.showForm = !$scope.showForm;
});
扩展名:
Angular 的使用适用于多种异步情况:
- 事件(ng-click 等)
- Ajax 调用
- 超时
当使用非平凡的异步操作时,绑定(bind)不会在分配后自动发生,因此最好使用 $apply。
关于javascript - 模型未在谷歌地图监听器中更新 - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28452166/