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

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

问题描述

我有一个这样的控制器:

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

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

  %= link_totest,,ng-click=> upload_variant_image()%> 

但是,在加载DOM后,这个元素是动态添加的,所以ng点击不起作用。



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



但是当我更新Rails中的DOM时,它不起作用:

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


解决方案

我会警告你,你可能没有完全拥抱如果您通过角度外部手段来操纵DOM,那么这个哲学哲学。与AngularJS动态添加链接与其他任何东西一样简单,并且可能会比使用外部库更好地使用起来更容易和更习惯。以下是一个基于您的问题的简单示例:

 < ul> 
< li ng-repeat =项目中的项目>
< a ng-click =upload_variant_image()> {{item.name}}< / a>
< / li>
< / ul>

所有您需要做的是适当地连接范围数据,这将永远正常工作。也就是说,如果你正在操纵DOM,你可以使用$compile服务。不过,请考虑以上更好的选择。 :)


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:

<%= 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.

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

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));

解决方案

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

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天全站免登陆