ng-click 不适用于动态 DOM AngularJS? [英] ng-click doesn't work on dynamic DOM AngularJS?

查看:31
本文介绍了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天全站免登陆