How to register my own event listeners in AngularJS?

Adding an event listener would be done in the linking method of a directive. Below I’ve written some examples of basic directives. HOWEVER, if you wanted to use jquery-ui’s .draggable() and .droppable(), what you can do is know that the elem param in the link function of each directive below is actually a jQuery object. So you could call elem.draggable() and do what you’re going to do there.

Here’s an example of binding dragstart in Angular with a directive:

app.directive('draggableThing', function(){ 
   return {
      restrict: 'A', //attribute only
      link: function(scope, elem, attr, ctrl) {
         elem.bind('dragstart', function(e) {
            //do something here.
         });
      }
   };
});

Here’s how you’d use that.

<div draggable-thing>This is draggable.</div>

An example of binding drop to a div or something with Angular.

app.directive('droppableArea', function() {
   return {
       restrict: 'A',
       link: function(scope, elem, attr, ctrl) {
            elem.bind('drop', function(e) {
                /* do something here */
            });
       }
   };
});

Here’s how you’d use that.

<div droppable-area>Drop stuff here</div>

I hope that helps.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)