如何在infowindow中触发事件。 我使用ng-click在google maps infowindow中有一个按钮。 当我点击它时,没有任何警报和错误。 有什么想法吗?
var infoWindow = new google.maps.InfoWindow({
maxWidth: 240,
content: "<button ng-click=\"test()\">Click me</button>"
});
测试功能。
$scope.test = function() {
alert('This is infowindow');
}
答案 0 :(得分: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>
答案 1 :(得分:2)