0

How can I add a jQuery click event to a li which has been dynamically generated by AngularJS

The Angular code / database / filtering is working perfectly, I just want to make it so that when you click on one of the li it does something.

I'm new to Angular

HTML

<li ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit" data-name="{{data.customerName}}" class="myli">
               <strong>{{data.customerName}}</strong><br />
               {{data.addressLine1}}, {{data.city}}, {{data.state}}, {{data.postalCode}}, {{data.country}}<br />
               <code>{{data.creditLimit}}</code>
</li>

jQuery

$(document).ready(function(){
        $(".myli").on("click", function(){
            var name = $(this).data("name");
            alert(name);
        });
});

Thanks

Rob
  • 738
  • 3
  • 10
  • 23

1 Answers1

0

Ideally you would leverage the ng-click https://docs.angularjs.org/api/ng/directive/ngClick functionality on your li

<li ng-click="eventHandler(data)" ... class="myli">

and then in your controller

scope.eventHandler = function(data){
     alert(data.name);
}

You've now removed your jquery dependency and you can change all the element types, classes, and even what you want to call your data element in markup without ever having to change your code in the controller

mikeswright49
  • 3,381
  • 19
  • 22
  • Thank you - this is perfect! – Rob Jul 16 '15 at 13:20
  • As a general plan whenever you are using angular and think "I can do this with Jquery" DON'T. Angular provides tools to do most of the UI manipulation and management that is historically done using JQuery. Take a look here: https://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background for tips – mikeswright49 Jul 16 '15 at 13:53