Search code examples
jqueryangularjsangularjs-directivejqlite

elem.find() is not working in AngularJS link


I have an Angular 'E' directive, from a templateUrl, that describes a table with ng-repeat generated rows. In my link designation, I'm trying to add an event listener to a button in that table.

directive:

    .directive("reqParts", ["$http", function($http){
   return {
       restrict: 'E',
       templateUrl: '/public/reqParts.html',
       link: function(scope, elem, attr){
           elem.find('.approve').click(function(){
               console.log("clicked");
           });
       }
   };

templateUrl:

<table class="table table-striped">
<tr>
    <th>User</th>
    <th>Title</th>
    <th>Waiting List</th>
</tr>
<tr ng-repeat="req in requests">
    <td>{{req.requestedBy[0].uname}}</td>
    <td>{{req.title}}</td>
    <td>{{req.requestedBy.length - 1}}</td>
    <td><button class='approve'>Approve</button></td>
</tr></table>

My load order is Jquery -> Bootstrap -> Angular -> AngularDirective, so that shouldn't be the problem, according to similar questions.

EDIT: Some things I've tried:

$('.approve').click() does not work.

console.log($('.approve')) returns [].

console.log(elem.children().children()) returns [tbody]

console.log(elem.find('button')) returns [].

elem.find('tr').click() works for the first row of the table, not the second (Shouldn't find give me the set of all elements matching the selector?)

In the console, $('.approve') works and `$('table').find('.approve') works.


Solution

  • Thanks for your suggestions guys! It turns out, the issue was not with JQuery, but with ng-repeat. I followed the workaround described here: AngularJS: Linking to elements in a directive that uses ng-repeat

    Creating a directive attribute that emits an event on the completion of ng-repeat works, and the second parameter passed is the JQuery wrapped row, which worked perfectly with .find()