3

如何在信息窗口中触发事件。我在谷歌地图信息窗口中有一个使用 ng-click 的按钮。当我单击它时,没有任何警报和错误。任何想法?

var infoWindow = new google.maps.InfoWindow({
    maxWidth: 240,
    content: "<button ng-click=\"test()\">Click me</button>"
});

测试功能。

$scope.test = function() {
   alert('This is infowindow');
}
4

2 回答 2

7

ng-click触发事件,需要使用$compile服务编译信息窗口内容。

例子

angular.module('map-example', [])
    .controller('MapController', function($scope, $rootScope, $compile) {


        function initialize() {

            $scope.map = new google.maps.Map(document.getElementById('map'), {
                zoom: 4,
                center: { lat: -38.363, lng: 131.044 }
            });



            $scope.cities = [
                { title: 'Sydney', lat: -33.873033, lng: 151.231397 },
                { title: 'Melbourne', lat: -37.812228, lng: 144.968355 }
            ];


            $scope.infowindow = new google.maps.InfoWindow({
                content: ''
            });


            for (var i = 0; i < $scope.cities.length; i++) {


                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng($scope.cities[i].lat, $scope.cities[i].lng),
                    map: $scope.map,
                    title: $scope.cities[i].title
                });

                var content = '<a ng-click="cityDetail(' + i + ')" class="btn btn-default">View details</a>';
                var compiledContent = $compile(content)($scope)

                google.maps.event.addListener(marker, 'click', (function(marker, content, scope) {
                    return function() {
                        scope.infowindow.setContent(content);
                        scope.infowindow.open(scope.map, marker);
                    };
                })(marker, compiledContent[0], $scope));

            }

        }

        $scope.cityDetail = function(index) {
            alert(JSON.stringify($scope.cities[index]));
        }

        google.maps.event.addDomListener(window, 'load', initialize);

    });
 html, body {
        height: 400px;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 400px;
      }
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div ng-app="map-example" ng-controller="MapController"> 
    <div id="map"></div>   
</div>

普朗克

于 2016-05-26T20:50:43.343 回答
2

干得好 :)

http://plnkr.co/edit/EbBWJQx5pOz0UyoayYFI?p=preview

通过等待信息窗口的“domready”然后编译来修复

于 2013-08-29T18:10:14.660 回答