0

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.

Gibryon Bhojraj
  • 755
  • 5
  • 12
  • 1
    jqlite, `find` is limited to tag lookup only – scniro Feb 27 '16 at 05:13
  • I just tried a JQLite suggestion- angular.element(document.getElementsByClassName('.approve')) - and that did not work either, so it's probably not a JQLite/Jquery problem and just something I did wrong. – Gibryon Bhojraj Feb 27 '16 at 05:13
  • I am loading JQuery before Angular though, so it should be overriding JQLite with JQuery. – Gibryon Bhojraj Feb 27 '16 at 05:15
  • have you tried `.on`? Check out [this example](https://jsfiddle.net/3gftoyct/) – scniro Feb 27 '16 at 05:24
  • 1
    @kondrak Thanks, but when what does this mean, from the Angular documentation for element: `If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or jqLite.` – Gibryon Bhojraj Feb 27 '16 at 13:58
  • @scniro Thank you for the fiddle. `elem.find('button').on()` did not work in my code, though. – Gibryon Bhojraj Feb 27 '16 at 14:29

1 Answers1

0

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

Community
  • 1
  • 1
Gibryon Bhojraj
  • 755
  • 5
  • 12