javascript - Angular Js - 操作 DOM 并添加点击行为

标签 javascript angularjs dom click dom-manipulation

我正在使用带 Angular 传单 map 并添加了图例。为了更改 map 的外观,我在使用 $timeout 方法加载 View 后操作了 DOM。图例应该是可点击的,以选择哪些项目应该出现在 map 上。因此,当单击图例中的一项时,我尝试发出警报。为此,我将项目更改为按钮只是为了确定。但是按钮点击不起作用,因为它不知道方法。

有人知道如何在被操纵的 DOM 对象上调用 ng-click 方法吗?

这是我的一些代码:

Controller .js

//initiating of the map happend before 
//now loading of the markers and manipulating of the map
function activate() {
    projectService.getMarkers(vm, 'projectsData');
    bindEventListener();

    $timeout( function() {
        getLegendElement();
    });
}

//manipulating of the legend element to make a button with a ng-click
function getLegendElement() {
    var element = document.getElementsByClassName("legend leaflet-control");
    element[0].children[0].innerHTML = '<button ng-click="showAlert()">ok</button>';
}

//showing the alert
$scope.showAlert = function(){
    $window.alert("foo");
}

最佳答案

您的 DOM 操作应该移至指令。但是,如果您想将它保留在您的 Controller 中,则需要将 $compile 注入(inject)您的 Controller 并在动态生成的 html 上调用它。

function getLegendElement() {
    var element = document.getElementsByClassName("legend leaflet-control");
    element[0].children[0].innerHTML = '<button ng-click="showAlert()">ok</button>';
    $compile(element)($scope);
}

这是因为 Angular 会在第一次解析模板时寻找它需要生成的事件绑定(bind)。由于您正在应用一个延迟事件,该事件需要绑定(bind)到最初解析您的模板时不存在的 html,因此您需要告诉 Angular 更新它对模板的理解。 documentation叫出来:

$compile

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

关于javascript - Angular Js - 操作 DOM 并添加点击行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29680268/

相关文章:

javascript - AngularJS:未捕获错误:[$injector:modulerr] 与 firebase

javascript - 为什么这个 jquery 不起作用?

javascript - ng-if 和 grid-tile 的问题

javascript - 如何获取jsp数据并显示在javascript函数的变量中

Javascript:对齐并行数组索引避免重叠

jquery - 当使用 .html 获取 jQuery 内容时,该内容会丢失 jQuery 功能。

javascript - 如何使用 MutationObservers 来查找元素的父元素何时从 DOM 中移除?

javascript - 为什么 .text().replace() 不适用于 td 元素? (jsfiddle)

javascript - Angular,需要通过多种形式检查 Controller

angularjs - Webstorm:无法解析对其他文件的 angularjs anchor (主题标签)引用