I'm attempting to create click-away functionality for an AngularJS directive (ie. when the user doesn't click a certain element, it hides).
I'm adding an event to $(body) which detects a click.
I then check whether either my directive or any of it's children have been clicked. If they haven't, it hides a div.
This works fine when I have one directive, but the moment I add a second of the same kind, it's the second that handles the $(body).click() event. The first doesn't get a look-in.
My code is as follows (I've removed much of it):
angular.module('ma.directives')
.directive('maDropdownPanel', function () {
var directiveId = null;
return {
restrict: "E",
transclude: true,
templateUrl: "maDropdownPanel.html",
scope: {},
link: function (scope, element, attributes) {
$('body').on('click', scope.handleClickAway);
// Get an ID unique to this particular directive.
directiveId = "ma-dropdown-panel" + scope.$id;
},
controller: function ($scope) {
$scope.handleClickAway = function (event) {
// The following shows which directive took it. Out of two, it's always the second (ie. the last to register the event).
console.log(directiveId);
}
}
}
});
I feel like if I can get the right one to be called, I can handle the rest.
Any help would be appreciated, thanks.