如何在AngularJS中动态编译HTML片段时绑定事件处理程序

jun*_*qiu 2 jquery openlayers angularjs angularjs-compile

我正在使用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);
};
Run Code Online (Sandbox Code Playgroud)

但是我现在正在努力处理事件处理程序,如果我更改template为(注意输入和ng-click跨度之后):

var template = "<div><span>{{data.text}}</span><input type='button' ng-click='func()' value='click me'/></div>";
Run Code Online (Sandbox Code Playgroud)

并在$scope以下位置定义事件处理程序

$scope.func = function() {
    console.log("Hello, world");
};
Run Code Online (Sandbox Code Playgroud)

但事件无法触发.我非常怀疑使用content.html()遗嘱会丢失一些有用的信息.当我尝试以下代码时:

    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);
Run Code Online (Sandbox Code Playgroud)

这个片段按预期完美地工作(ng-click也可以在这里工作).这两种用法的唯一区别是:contentcontent.html().

但我不能使用content给定的OpenLayers.Popup.FramedCloud静态html内容字符串.

有关于此的任何想法?非常感谢你.

Tia*_*hai 5

我遇到了同样的问题,花了3天时间才找到解决方案.最后我发现解决方案是在弹出窗口添加到地图后调用$ compile函数.看到这个小提琴. Angularjs的Openlayers

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);
Run Code Online (Sandbox Code Playgroud)

将弹出窗口添加到地图后,将创建一个新的dom.使用Angularjs的jqlite,我们可以获取dom并根据范围对其进行编译,以使其绑定到您需要调用的方法.