ng-click在动态DOM AngularJS上不起作用? [英] ng-click doesn't work on dynamic DOM AngularJS?

查看:135
本文介绍了ng-click在动态DOM AngularJS上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的控制器:

I have a controller like this:

@VariantModalCtrl = ($scope) ->
  $scope.upload_variant_image = ->
    alert("test")

当我尝试使用ng-click调用upload_variant_image函数时,它仅在绑定到静态DOM(加载DOM时)才有效,我有这样的链接:

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:

<%= link_to "test", "" , "ng-click" => "upload_variant_image()" %>

,但是此元素是在DOM加载后动态添加的,因此ng-click不起作用.

but this element is dynamically added after the DOM is loaded, so ng-click doesn't work.

更新 刚刚使用$ compile函数找到了我的答案的一部分: AngularJS + JQuery:如何使动态内容在angularjs中工作

Update Just found part of my answer using $compile function: AngularJS + JQuery : How to get dynamic content working in angularjs

但是当我在Rails中像这样更新DOM时,它不起作用:

BUT it doesn’t work when I update the DOM like this in Rails:

$(".modal-body").html($compile("<%= j render("/variants/form", :variant => @variant) %>")(scope));

推荐答案

我会警告您,如果您通过Angular外部方法来操纵DOM,则可能不会完全接受Angular哲学.使用AngularJS动态添加链接就像其他任何事情一样简单,并且比使外部库运行得更好更容易,而且更加惯用.这是一个基于您的问题的简单示例:

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:

<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."

也就是说,如果您要操作DOM,则可以使用$compile服务.不过,请考虑上述更好的选择. :)

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. :)

这篇关于ng-click在动态DOM AngularJS上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆