allenhwkim
allenhwkim

Reputation: 27748

AngularJS google maps infoWindow is not compiled

I tried to implement google maps infoWindow using AngularJS.

I have a template <div>{{foo}}<br/>, with $scope.foo="bar"

I want to see the info window with the value "bar" instead of seeing "{{foo}}". Thus, I compiled and set the contents with it, but no luck yet.

Some may think this is duplicate to AngularJS ng-include inside of Google Maps InfoWindow?, but I want to compile contents dynamically.

Here is the code I have now, 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);
  })

I was thinking $scope.apply(), but was not able to run in the code.

Is there a way to have google maps InfoWindow $compiled?

Upvotes: 4

Views: 1116

Answers (1)

Blaise
Blaise

Reputation: 13489

You're almost there!

You're right about needing to do a $scope.$apply to trigger parsing of template x, but since you're already in the middle of a digest cycle, calling $scope.$apply will give you a $rootScope:inprog error. You'll need to create a new digest cycle where you call $scope.$apply:

$scope.$evalAsync(function() {
  $scope.$apply();
  infowindow.setContent(el.html());
  infowindow.open(map);          
});

Upvotes: 0

Related Questions