This is a migrated thread and some comments may be shown as answers.

Capture click event on AngularJS sortable items

1 Answer 243 Views
Sortable
This is a migrated thread and some comments may be shown as answers.
Pablo
Top achievements
Rank 1
Pablo asked on 12 Dec 2014, 12:45 PM
In this example I have an AngularJS sortable that contains three divs. My objective is to obtain the id and the text of the div that was clicked, however the click event is not triggered. What's wrong with this code?


This is the javascript:

    var app = angular.module("app", [ "kendo.directives" ]);
    
   
  app.directive('dir2', function() {

    var directive = {};

         directive.restrict = 'EA';

         directive.template = '<div kendo-sortable="list" id="listid"></div>';

         directive.link = function(scope, element, attrs) {

        scope.$on("kendoWidgetCreated", function(event, widget){
 
              if (widget === scope.list) {
                         $('#listid').append ( '<div id="div1" class="item">11111111</div>');  
                         $('#listid').append ( '<div id="div2" class="item">22222222</div>');
                         $('#listid').append ( '<div id="div3" class="item">33333333</div>');
                 }

           });


          $('.item').on( "click", function( event ){

                         alert('clicked');
                         console.log(event);
          });


        };

        return directive;
  });

1 Answer, 1 is accepted

Sort by
0
Alexander Valchev
Telerik team
answered on 16 Dec 2014, 09:29 AM
Hi Pablo,

The plnkr example does not load on my end. Anyway, I believe that the issue occurs because at the time when the click event is hooked up the items are not present in the DOM (they are added later and the kendoWidgetCreated event).

Please delegate the click event on the parent container:

scope.$on("kendoWidgetCreated", function(event, widget){
 
    if (widget === scope.list) {
      $('#listid').append ( '<div id="div1" class="item">11111111</div>'); 
      $('#listid').append ( '<div id="div2" class="item">22222222</div>');
      $('#listid').append ( '<div id="div3" class="item">33333333</div>');
    }
 
    scope.list.element.on("click", ".item", function() { /* your code */ });
 
});

I hope this approach will fit in your scenario.

Regards,
Alexander Valchev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Sortable
Asked by
Pablo
Top achievements
Rank 1
Answers by
Alexander Valchev
Telerik team
Share this question
or