我将OpenLayers与AngularJS结合使用,一切进行得很好,直到最终开始接触弹出功能为止。
我知道如何使用$compile
服务通过以下方式使动态内容显示在弹出窗口中:
$scope.data = {
text: "Dynamic content"
};
var template = "<div><span>{{data.text}}</span></div>";
$scope.showPopup = function() {
var content = $compile(template)($scope);
var lonlat = "-5694.06868525478, 6708925.0877411375";
$timeout(function() {
var popup = new OpenLayers.Popup.FramedCloud("popup",
OpenLayers.LonLat.fromString(lonlat),
null,
content.html(),
null,
true
);
map.addPopup(popup);
}, 0);
};
但是如果我将
template
更改为(请注意输入和跨度后的ng-click
),那么我现在正在努力处理事件处理程序:var template = "<div><span>{{data.text}}</span><input type='button' ng-click='func()' value='click me'/></div>";
并在
$scope
中定义事件处理程序:$scope.func = function() {
console.log("Hello, world");
};
但事件无法触发。我非常怀疑使用
content.html()
是否会丢失angularjs关心的一些重要信息。当我尝试以下代码时: var template = "<div><span>{{data.text}}</span><input type='button' ng-click='func()' value='click me'/></div>";
var content = $compile(template)($scope);
angular.element("#footer").append(content);
此代码段可以按预期完美运行(ng-click也可以正常运行)。这两种用法之间的唯一区别是:
content
和content.html()
。但是我不能使用
content
,因为OpenLayers.Popup.FramedCloud
需要一个静态的html内容字符串。有什么想法吗?
非常感谢你。
最佳答案
我遇到了同样的问题,花了3天的时间找到解决方案。最后,我发现解决方案是在将弹出窗口添加到地图后调用$ compile函数。看到这个小提琴。
Openlayers with Angularjs
var template = "<div><span>{{halo}}</span><button ng-click='call()'>call</button></div>";
var popup = new OpenLayers.Popup.FramedCloud("popup", new OpenLayers.LonLat(103.83641, 1.35578), null, template, null, true);
map.addPopup(popup);
var pp = angular.element(document.querySelector('#popup'));
$compile(pp)($scope);
将弹出窗口添加到地图后,将创建一个新的dom。使用Angularjs的jqlite,我们可以获得dom并根据范围对其进行编译,以使其绑定到您需要调用的方法。