我正在使用带 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/