angular.module('agileApp').directive('offClick', ['$document', '$timeout', function ($document, $timeout) { return { link: function postLink(scope, element, attrs) { var onClick = function (event) { console.log("scanning"); var isChild = $(element).has(event.target).length > 0; var isSelf = element[0] == event.target; var isInside = isChild || isSelf; if (!isInside) { scope.$apply(attrs.offClick) } } scope.$watch(attrs.isActive, function(newValue, oldValue) { $timeout(function(){ // okay we have to stop propigation because the event bubbles up to the document who will //immediately fire our off click event handler if (newValue !== oldValue && newValue == true) { $document.bind('click', onClick); console.log("bound"); } else if (newValue !== oldValue && newValue == false) { $document.unbind('click', onClick); console.log("unbound"); } }); }); } }; }]);