Nik Nik - 3 months ago 9
Javascript Question

Using jquery with dynamically created elements from angular doesnt work

Im trying to use jquery to manipulate elements created by angular, but I am not able to get it to work. I was wondering if anyone could help me out. Thanks

Here is the HTML

<div class="patients">
<tbody ng-repeat="patient in patients">
<tr>
<td>{{patient.name}}</td>
<td>{{patient.number}}</td>
<td>{{patient.date}}</td>
<td id="item-{{$index}}">{{patient.reminded}}</td>
<div class="sendreminder">
<td>
<a href="" class="btn btn-info btn-sm sendreminder" style=" background-color: #00e699; border-color:#00e699; " ng-click="post($index) " "$parent.selected = $index" id="button-{{$index}}">
<span class="glyphicon glyphicon-send"></span> Request Payment
</a>
</td>
</div>
<td>
<a href="" style="text-decoration:none; color:inherit; scale: 4" class="pe-7s-info">
</a>
</td>
</tr>

</tbody>
</div>


Here is the jquery

$(function() {
$('.patients').on('click', ".sendreminder",function(e){
alert('worked');
});

});

Answer

ng-repeat recreates DOM everytime it detects changes(and hence, all the attached events will be gone). So to reattach the events after ng-repeat finishes, you can do

<tbody ng-repeat="patient in patients" ng-init="$last && ngRepeatFinish()">

$last will be set to true if its the last item for ng-repeat

and in you controller, create ngRepeatFinish() function

$scope.ngRepeatFinish = function(){
    $('.sendreminder').click(function(e){
         alert('worked');
    });
}

you can also make custom directives for this which is better than this, but this will suffice for a quick solution. See this for a solution with custom directives