javascript ng-click 对动态 DOM AngularJS 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16296264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-click doesn't work on dynamic DOM AngularJS?
提问by user1883793
I have a controller like this:
我有一个这样的控制器:
@VariantModalCtrl = ($scope) ->
$scope.upload_variant_image = ->
alert("test")
When I try to call upload_variant_image function using ng-click, it only works when binding to a static DOM (when the DOM loads), I have a link like this:
当我尝试使用 ng-click 调用 upload_variant_image 函数时,它仅在绑定到静态 DOM 时有效(当 DOM 加载时),我有一个这样的链接:
<%= link_to "test", "" , "ng-click" => "upload_variant_image()" %>
but this element is dynamically added after the DOM is loaded, so ng-click doesn't work.
但是这个元素是在 DOM 加载后动态添加的,所以 ng-click 不起作用。
UpdateJust found part of my answer using $compile function: AngularJS + JQuery : How to get dynamic content working in angularjs
更新刚刚使用 $compile 函数找到了我的部分答案: AngularJS + JQuery : How to get dynamic content working in angularjs
BUT it doesn't work when I update the DOM like this in Rails:
但是当我在 Rails 中像这样更新 DOM 时它不起作用:
$(".modal-body").html($compile("<%= j render("/variants/form", :variant => @variant) %>")(scope));
回答by Ezekiel Victor
I would warn you that you may not be fully embracing Angular philosophy if you're manipulating the DOM through Angular-external means. Adding links dynamically with AngularJS is as simple as anything else and will probably be much easier and more idiomatic than getting your external library to play nice. Here is a simple example based on your question:
我要警告您,如果您通过 Angular 外部方式操作 DOM,您可能没有完全接受 Angular 哲学。使用 AngularJS 动态添加链接和其他任何事情一样简单,并且可能比让外部库正常运行更容易和更惯用。这是一个基于您的问题的简单示例:
<ul>
<li ng-repeat="item in items">
<a ng-click="upload_variant_image()">{{item.name}}</a>
</li>
</ul>
All you need to do is wire up the scope data appropriately and this will always "just work."
您需要做的就是适当地连接示波器数据,这将始终“正常工作”。
That said, if you are manipulating the DOM, you can cause AngularJS bindings to occur (to, say, ng-click as you desire) by using $compile service. Do consider the above better option, though. :)
也就是说,如果您正在操作 DOM,您可以通过使用$compile service导致 AngularJS 绑定发生(例如,根据需要进行 ng-click)。不过,请考虑上述更好的选择。:)