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

11,583

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

Share:
11,583
user1883793
Author by

user1883793

Updated on June 22, 2022

Comments

  • user1883793
    user1883793 about 2 years

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