jQuery and AngularJS: Bind Events to Changing DOM

Answer here:

This is a multifaceted question. First of all, all jQuery code events should use $scope.$apply to execute angularjs code as expected. Example:

jQuery(selector).someEvent(function(){
    $scope.$apply(function(){
      // perform any model changes or method invocations here on angular app.
    });
});

In the latest version of jQuery, in order to have events that update based on DOM changes, you want to 1. Get a selector for the nearest parent element (ex):

<div class="myDiv">
<div class="myDynamicDiv">
</div>
<!-- Expect that more "myDynamicDiv" will be added here -->
</div>

In this case, your parent selector would be “.myDiv”, and your child selector would be .myDynamicDiv.

Thus, you want jQuery to have the events on the PARENT of the element so if the child elements change, it will still work:

$('.myDiv').on("click", ".myDynamicDiv", function(e){
      $(this).slideToggle(500);
      $scope.$apply(function(){
           $scope.myAngularVariable = !$scope.myAngularVariable;
      });
});

Notice that the $scope.$apply() is used in order to enable jQuery to access those angular variables.

Hope this helps!
Christian

Leave a Comment