I am seeking to understand the order in which events fire within an AngularJS context.
I have a directive in which there is an event listener:
angular.module('myApp').directive('myDirective', ['$document', function ($document) {
function link (scope, element, attrs) {
$document.on('mouseup', function (event) {
event.stopPropagation();
console.log("mouse up heard");
})
}
return {link:link}
}
I also have an generic view, in which I use this directive.
<div ng-click="listenForClick()">
<div my-directive>
</div>
</div>
In the controller, I've got:
angular.module('myApp').controller('myController', ['$scope', function ($scope) {
$scope.listenForClick = function() {
console.log("I want to block the mouse up from being heard here!!");
//Unfortunately, as I have it right now, this console.log is still showing.
}
}]);
At first, I thought it may have been because the event target was on the document, and there was nothing to propagate up to (i.e. listenForClick() already had happened, since it is inside the document). However, the order of the console.log messages is:
"mouse up heard"
"I want to block the mouse up from being heard here!!"
The is the opposite of what I thought had happened. This indicates that the event first hit the document listener within myDirective, and then hit ng-click, as the DOM would suggest, but somehow stopPropogation failed.
Questions:
Why is stopPropogation failing? And how would you achieve the intended effect?
I am little confused because normally, with JQuery, for example, you attach the event listener on an element in the DOM tree, and the hierarchy of the DOM tree decides which listeners are heard first. In the case above, however, I am dealing with a directive attached to a plain old div, in which I have my listener, but I have actually attached the listener to a $document. Question: What is the event listener actually attached to, and how do you explain the order of the messages above? How is angular dealing with the events and the multiple directives?