动态创建的元素未触发点击事件 [英] Dynamically created element not firing click event
问题描述
$scope.addNew = function(){
$('.thumb-img-gallary').append("<li><span class='img-del' ng-click='delThumbImgGallaryPhoto($event)'>X</span><img class='thumb-img' src='data:image/jpeg;base64,"+imageData+"'/></li>");
}
我正在调用此函数来动态添加元素.但是然后delThumbImgGallaryPhoto()
没有被调用.
I am calling this function to add element dynamically. But then delThumbImgGallaryPhoto()
is not getting called.
推荐答案
您不能仅通过ng-click或任何其他指令附加元素,并期望它起作用.它必须按角度进行编译.
you cannot just append an element with a ng-click or any other directive, and expect it to work. it has got to be compiled by angular.
关于有角度的文档的编译说明:
explenation about compilation from angular docs:
对于AngularJS,编译"是指在HTML上附加指令以使其具有交互性
For AngularJS, "compilation" means attaching directives to the HTML to make it interactive
在以下两种情况之一中发生争斗:
compelation happens in one of two cases:
当Angular引导您的应用程序时,HTML编译器会针对DOM元素遍历DOM匹配指令
When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements
当您在尖角内调用 $ compile 服务时上下文
when you call the $compile service inside an angular context
因此,您需要做的是首先对其进行编译(注意在控制器中注入$ compile服务),然后将其附加:
so what you need to do, is first to compile it(remeber to inject the $compile service in your controller), and then append it:
$scope.addNew = function(){
var elem = $compile("<li><span class='img-del' ng-click='delThumbImgGallaryPhoto($event)'>X</span><img class='thumb-img' src='data:image/jpeg;base64,"+imageData+"'/></li>")($scope);
$('.thumb-img-gallary').append(elem);
}
顺便说一句,请记住最好不要在控制器中进行任何DOM操作.角对此有指令.
BTW, remember it is prefable not to have any DOM manipulations done in the controller. angular has directives for that.
这篇关于动态创建的元素未触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!