Capture click event on AngularJS sortable items

2 posts, 0 answers
  1. Pablo
    Pablo avatar
    3 posts
    Member since:
    Dec 2014

    Posted 12 Dec 2014 Link to this post

    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;
      });
  2. Alexander Valchev
    Admin
    Alexander Valchev avatar
    2877 posts

    Posted 16 Dec 2014 Link to this post

    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!
     
  3. Kendo UI is VS 2017 Ready
Back to Top