Last active
August 29, 2015 14:07
-
-
Save Luxiyalu/eccc8c4f864e42f6d197 to your computer and use it in GitHub Desktop.
AngularJS: Click Outside of Directory
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
app.controller 'AppCtrl', ($rootScope) -> | |
# broadcast click event within AppCtrl | |
$(document).on 'click', (e) -> | |
$rootScope.$broadcast 'click', e.target | |
# this target is a js dom element |
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
app.directive 'dropdownBox', ($rootScope) -> | |
scope: {} | |
link: (scope, element, attr) -> | |
# listen to click event, within a link function: | |
offEvent = $rootScope.$on 'click', (e, target) -> | |
if !element.find($(target)).length # clicked outside of directory | |
# equivalent to: !($.contains(element[0], target) || element.is(target)) | |
scope.showDropdown = false | |
scope.$apply() | |
# don't forget to apply! since angular has already digested the whole click | |
# before jquery's event, without $apply it wouldn't be applied at this point | |
# don't forget to turn off the event when scope is destroyed | |
$scope.$on '$destroy', -> do offEvent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment