Skip to content

Instantly share code, notes, and snippets.

@JonathanTech
Last active August 29, 2015 14:03
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 JonathanTech/202665b44c9564621e51 to your computer and use it in GitHub Desktop.
Save JonathanTech/202665b44c9564621e51 to your computer and use it in GitHub Desktop.
.directive('clickOutside', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function link(scope, iElement, iAttrs) {
var eventHandler = $parse(iAttrs.clickOutside),
clickEvalFunction = function (e) {
var container = $(iElement);
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
scope.$apply(function () {
eventHandler(scope, { $event: e });
});
}
};
scope.$watch(function (scope) {
return typeof (iAttrs.clickOutsideConditional) == 'undefined' || scope.$eval(iAttrs.clickOutsideConditional) ;
}, function (newValue) {
if (newValue) {
$(document).on('click touchstart', clickEvalFunction);
} else {
$(document).off('click touchstart', clickEvalFunction);
}
});
iElement.on('$destroy', function() {
$(document).off('click touchstart', clickEvalFunction);
});
}
}
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment