Search code examples
angularjsleafletmustacheangular-leaflet-directive

Angular dynamically generated code on leaflet map


I have some application in angular. That is my html code.

<div ng-app="mapApp">
    <div ng-controller="mainController">
       <leaflet id="map" center="center" height="640px" width="100%"></leaflet>
    </div>
</div>
<div id="templates">
    <script type="text/html" id="someTemplate">
        <div>
            // need Angular scope here!
            <h4>{{label}}</h4>
            <button class="btn btn-primary" ng-click="{{someFunction}}">
            </button>
        </div>
    </script>
</div>

Javascirpt Controller implementation:

app.controller("mainController", function($scope,  $rootScope, $compile, leafletData) {
   $scope.map = null;
   $scope.template = $("#someTemplate").html();

   leafletData.getMap('map').then(function(map) {
        $scope.map = map;
   });

   $scope.drawSomePopup = function(object) {
       var popupElement = Mustache.to_html($scope.template, templateData)

       var popup = L.popup().setContent(popupElement);
       var poly = L.polygon(object.boundary.geoPoint, {color: 'red'})
                .addTo($scope.map)
                .bindPopup(popup);
   };

   drawSomePopup($rootScope.someObject);

   $scope.someFunction = function(object) {
       //some operations
   };
}

I was trying to use $compile service on generated element, but it doesn't work. Solution like:

$compile( $("map") )

also doesn't work. Global function onclick on templated element is some solution but i want to avoid this.

Is some solution for this example ?


Solution

  • I found solution.

    $scope.drawSomePopup = function(object) {
        var popupContent = Mustache.to_html($scope.template, templateData); 
        var popup = L.popup();
        var linkFunction = $compile(angular.element(popupContent));
        popup.setContent(linkFunction($scope)[0]);
    
        var poly = L.polygon(object.geoPoint, {color: 'red'}).addTo($scope.map);
        poly.bindPopup(popup);
    };
    

    Popup must be recompiled first, but then appended to DOM.