Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register my own event listeners in AngularJS?

How do I register my own event listeners in an AngularJS app?

To be specific, I am trying to register Drag and Drop (DND) listeners so that when something is dragged and dropped in a new location of my view, AngularJS recalculates the business logic and updates the model and then the view.

like image 200
Tonte Pouncil Avatar asked Oct 13 '12 16:10

Tonte Pouncil


People also ask

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

Which function should we use to add event listener in a directive?

The ngOn directive adds an event listener to a DOM element via angular. element(). on(), and evaluates an expression when the event is fired.

How many listeners can be attached to an event?

The maximum number of event listeners that can be attached to the event can be set by the setMaxListeners function and the default value is 10.

What is event binding in AngularJS?

In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component.


1 Answers

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.

like image 133
Ben Lesh Avatar answered Sep 20 '22 22:09

Ben Lesh