Angular 在传单地图上动态生成代码

Angular dynamically generated code on leaflet map

我在 angular 有一些申请。那是我的 html 代码。

<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 控制器实现:

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
   };
}

我试图在生成的元素上使用 $compile 服务,但它不起作用。解决方案如:

$compile( $("map") )

也不行。模板元素上的全局函数 onclick 是一些解决方案,但我想避免这种情况。

这个例子有一些解决方案吗?

我找到了解决方案。

$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,然后附加到 DOM。