4

我尝试使用 AngularJS 实现谷歌地图 infoWindow。

我有一个模板<div>{{foo}}<br/>,有$scope.foo="bar"

我想查看值为“bar”的信息窗口,而不是查看“{{foo}}”。因此,我用它编译并设置了内容,但还没有运气。

有些人可能认为这与 Google Maps InfoWindow 中的 AngularJS ng-include重复 ?,但我想动态编译内容。

这是我现在拥有的代码,http ://plnkr.co/edit/RLdAcaGz5FfmJEZi87ah?p=preview

  angular.module('myApp', []).controller('MyCtrl', function($scope, $compile) {
    var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
    var mapOptions = { zoom: 4, center: myLatlng };

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var infowindow = new google.maps.InfoWindow({position: myLatlng});

    var x = "<div>{{foo}}<br/>{{foo}}";
    $scope.foo="bar";
    var el = $compile(x)($scope);
    infowindow.setContent(el.html());
    infowindow.open(map);
  })

我在想$scope.apply(),但无法在代码中运行。

有没有办法让谷歌地图 InfoWindow $compiled?

4

1 回答 1

0

您快到了!

您需要执行 a$scope.$apply来触发对 template 的解析是正确的x,但是由于您已经处于摘要周期的中间,因此调用$scope.$apply会给您一个$rootScope:inprog错误。您需要创建一个新的摘要循环,您可以在其中调用$scope.$apply

$scope.$evalAsync(function() {
  $scope.$apply();
  infowindow.setContent(el.html());
  infowindow.open(map);          
});
于 2015-06-07T16:50:09.957 回答