Created
May 14, 2016 10:16
-
-
Save mzahor/48fd1b1360689ea5e9d869d46c0c8626 to your computer and use it in GitHub Desktop.
Click outside angular directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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