Skip to content

Instantly share code, notes, and snippets.

@mzahor
Created May 14, 2016 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzahor/48fd1b1360689ea5e9d869d46c0c8626 to your computer and use it in GitHub Desktop.
Save mzahor/48fd1b1360689ea5e9d869d46c0c8626 to your computer and use it in GitHub Desktop.
Click outside angular directive
let hookInstalled = false;
function ClickOutsideDirective($window, $rootScope, $parse) {
'ngInject';
return {
restrict: 'A',
link: function(scope, elem, attr) {
if (!hookInstalled) {
$window.document.addEventListener('click', function(event) {
$rootScope.$broadcast('click', {
event
});
});
}
let unsubscribe = $rootScope.$on('click', function() {
if (!elem[0].contains(event.target)) {
scope.$apply(function() {
$parse(attr.clickOutside)(scope);
});
}
});
scope.$on('$destroy', () => {
unsubscribe();
});
}
};
}
export default {
directive: ClickOutsideDirective,
register: module => {
module.directive('clickOutside', ClickOutsideDirective);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment