user1883793
user1883793

Reputation: 4189

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

Upvotes: 10

Views: 11645

Answers (1)

Ezekiel Victor
Ezekiel Victor

Reputation: 3876

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

Upvotes: 15

Related Questions