简体   繁体   中英

ng-click doesn't work on dynamic DOM AngularJS?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM