How to trigger an event in AgularJS, as in jQuery?

Is it possible to do something like $("#container").trigger("click"); using only AngularJS? And if it is not possible to trigger , is there another way to control this behavior?

I have a basic example that creates a window when a button is clicked. The created box is dragged. Now, for now, the user must click on the button (to create the window) and click again to drag the window. I would like the user to simply click once: to create a window and then trigger a window drag event so that the user does not have to click again.

 var app = angular.module("app", []); // This directive is attached to the button and makes it create a box every time the is a 'mousedown' event app.directive("boxCreator", function($document, $compile) { return { restrict: 'A', link: function($scope, $element, $attrs) { $element.bind("mousedown", function($event) { var newNode = $compile('<div class="box" drag></div>')($scope); newNode.css({ top: $event.pageY - 25 + "px", left: $event.pageX - 25 + "px" }); angular.element($document[0].body).append(newNode); // I'd like to do something like : '$(newNode).trigger("mousedown");' }); } } }); // Makes the binded element draggable app.directive("drag", function($document) { return function(scope, element, attr) { var startX = 0, startY = 0, x = event.pageX - 25, y = event.pageY - 25; element.css({ position: 'absolute', cursor: 'pointer' }); element.on('mousedown', function(event) { event.preventDefault(); startX = event.pageX - x; startY = event.pageY - y; $document.on('mousemove', mousemove); $document.on('mouseup', mouseup); }); function mousemove(event) { y = event.pageY - startY; x = event.pageX - startX; element.css({ top: y + 'px', left: x + 'px' }); } function mouseup() { $document.off('mousemove', mousemove); $document.off('mouseup', mouseup); } }; }); 

JSFIDDLE

+5
source share
2 answers

The documentation you want to see is angular.element , which is an implementation of angular JQLite.

You can see from this that the .triggerHandler() method .triggerHandler() .

So something like:

 angular.element(newNode).triggerHandler('mousedown'); 

Call handler. The only thing is that this does not include any event data, so you will also have to remove the dependency on event.pageY . I did it roughly by changing these two lines:

 startX = (event.pageX - x) || 0; startY = (event.pageY - y) || 0; 

You can also see the passing options, but I couldn't get this to work at all.

Hope this helps you.

Updated script

+5
source

You can use triggerHandler and pass custom event data.

 element.triggerHandler({ type: 'mousedown', pageX: 0, pageY: 0 }); 
+1
source

Source: https://habr.com/ru/post/1202002/


All Articles